Search code examples
underscore.jsunderscore.js-templating

UnderscoreJS - how to get first instance of value from the array of objects?


In my array, I have no.of instance label with code. But i required just one from the first instance. I used the find method. But i am getting error.

here is my try:

var ob = {
    "name" : [
        {"code" : ""},
        {"code" : "1"},
        {"code" : "1"},
        {"code" : "1"},
        {"code" : "1"}
    ]
}

var code = _.find(ob.name, "code");
console.log(code); //error as "undefined is not a function"

the method which is use here is wrong? can any one guide me the correct one please?

Live Demo


Solution

  • If you want to get the first element from the array, use _.first():

    var code = _.first(ob.name).code;
    

    Or

    var code = _(ob.name).pluck('code').first();
    

    If you want to get non-empty first element, use filter to filter out the empty elements.

    _(ob.name).pluck('code').filter(function (e) { return !!e; }).first();