0

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

1
  • You either need to pass a function as the second argument to _.find. What did you think would a string do? Commented Sep 18, 2014 at 10:27

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

in case if i decide to check 2 property how can i handle that? example ({"code" : "1", sec:"1"}).. do i need to write 2 return functions or i can accommodate with one?
In that case, omit pluck function. Then you will get the each object that has two fields. You can use the property in the filter function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.