2

Hi I'm trying to perform _.find using underscore function. When I tried to execute it, it returns undefined, but all my string search from this object is always there. Please find below my sample data structure:

oArrays = [
  { 
    "c":"ABC", 
    "sc":[
      { "name":"ABC123", "t1":0, "t2":0 },
      { "name":"ABC456", "t1":0, "t2":0 },
      { "name":"ABC789", "t1":0, "t2":0 }
    ] 
  },
  { 
    "c":"BCDEF", 
    "sc":[
      { "name":"JJHS", "t1":0, "t2":0 },
      { "name":"JKHJYH", "t1":0, "t2":0 },
      { "name":"DKJHKJ", "t1":0, "t2":0 }
    ] 
  },
  { 
    "c":"ZYXV", 
    "sc":[
      { "name":"KDSKD", "t1":0, "t2":0 },
      { "name":"PWIFGF", "t1":0, "t2":0 },
      { "name":"WWSD", "t1":0, "t2":0 }
    ] 
  }, 
]

_.find(oArrays, function(item){
   return item.sc.name==="ABC123" ;
});

the above codes doesn't worked, result is undefined.... Is it possible to execute it in one _.find function only?

I tried to used multiple _.map function, it works. But as much as possible I dont want to use it coz it will have too many loops. (sample below)

_.map(oArrays, function(item){
  _.find( item.sc, function( item2 ) {
    return item2.name==="ABC123" ;
  });
});

Ooops, btw I'm executing these codes using sails-controller.

really appreciate any help :)

Thanks in advance!

1 Answer 1

4

item.sc.name is never a string, as you're trying to compare it to. In fact, it's actually undefined. But item.sc is an array of objects with the name property.

You have to check if among the name properties there's what you're looking for:

_.find(oArrays, function(item) {
    return _.contains(_.pluck(item.sc, "name"), "ABC123");
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi MaxArt thanks so much for your reply, I ran this code and it works, it returned the object of matched search.
Also, is it possible that inside the _.find function can also retrieve the second-level index of found search?
@Nina Yes. Instead of _.contains, you can use _.indexOf: this will return the index of the item with the name you're looking for, or -1 if not found. Then you can do return index !== -1;.

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.