# Getting the first selected item from a list of Backbone models

Current code (ES6):

getSelectedItem() {
let result;
return ((result = this.getItems().map((s) => {
return Util.isItemSelected(s.toJSON()) ? s.toJSON() : false;
}).filter(Boolean)) && result.length) ? result[0] : null;
},


s is a Backbone.js Model (hence the need to .toJSON() on it).

Apart from a very generic, "How can I improve this?", I'm specifically looking to reduce the duplication of .toJSON(), the anonymous function I pass into .map() and then also the need to declare result outside of my return statement.

I assume you want to return the first model from an array of models. Since you're using Backbone, you'll be able to use Underscore. So, if first model has length, return it:


function getItems() {
var model1 = new Backbone.Model({
firstName: "Wassily",
lastName: "Kandinsky"
});

var model2 = new Backbone.Model({
firstName: "Jhon",
lastName: "Doe"
});

var model3 = new Backbone.Model({
firstName: "Jane",
lastName: "Doe"
});
return [model1, model2, model3]

}

function getSelectedItem() {
var isFilled =  _.map(getItems(), function (s) {
return s.toJSON();
});
return isFilled.length ? isFilled[0] : null;
}

console.log(getSelectedItem().firstName);



I do not use Util since I don't know what that is but it shoudn't be neccesary. You can test it here: http://jsfiddle.net/jgauna/Lnmsp6jf/

Instead of creating an anonymous function, you could reduce it to a (long) one liner:

return ((result = this.getItems().map((s) => Util.isItemSelected(s.toJSON()) ? s.toJSON() : false).filter(Boolean)) && result.length) ? result[0] : null;


(Notice how you don't need to use the curly brackets and a return statement, we just point to what we want)

Unfortunately, I don't think it's possible to take out the instances of result and .toJSON(), maybe refactoring it like this would make it look a bit better?

getSelectedItem() {
let result = this.getItems().map((s) => {
let json = s.toJSON();
return Util.isItemSelected(json) ? json : false;
};
return (result.filter(Boolean)) && result.length) ? result[0] : null;
},