0

I have a sample array of objects as below, I want the one of the object in the array which has name Test.

**Results: [
 { Name: "Test",
   Age :21
   ChildrenObj:
 },
 { Name: "Something else",
   Age :21
   ChildreObj
 }**

I am using the below code to find it, and it is not returning me the correct data

var names= (_un.find(data.Results, function(item) {
        return item.Name= "Test"; 
    }));

any direction will be appreciated.

6
  • 2
    return item.Name=="Test" Test for equality, don't do assignment. Commented Aug 11, 2016 at 20:49
  • @will, thank you very much. Silly mistake i did. Thats why i am getting all the data assgined to it. Commented Aug 11, 2016 at 20:50
  • 1
    Even better, use === (3 equals) preferably. This also makes sure that they are the same type! 1=="1" is true, but 1 === "1" is not Commented Aug 11, 2016 at 20:52
  • Did it work out? @kobe Commented Aug 12, 2016 at 17:54
  • @anokrize, it worked. Commented Aug 12, 2016 at 22:09

4 Answers 4

2

Here's a working example, just for fun.

var Results = [{
  Name: "Test",
  Age: 21,
  ChildrenObj: {}
}, {
  Name: "Something else",
  Age: 21,
  ChildrenObj: {}
}];

var names = (_.find(Results, function(item) {
  return item.Name == "Test";
}));

console.log(names);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

2

var data = [{ 
   Name: "Test",
   Age :21
 },
 { Name: "Something else",
   Age :22
 }];
 
 
console.log(_.findWhere(data, {Age: 22}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Comments

1

Try this:

return item.Name == "Test";

You are doing an assignment not a comparisson.

Results: [
 { Name: "Test",
   Age :21
   ChildrenObj:
 },
 { Name: "Something else",
   Age :21
   ChildreObj
 }

Comments

1

You can use filter

results = [
 { Name : "Test",
   Age : 21,
   ChildrenObj : null
 },
 { Name : "Something else",
   Age :21,
   ChildrenObj : null
 }];
var names = results.filter(x => x.Name === "Test");
console.log(names); // [ { Name: 'Test', Age: 21, ChildrenObj: null } ]

Comments

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.