1

I am trying to filter an array of objects by its content, i.e.:

https://jsfiddle.net/z7g3unyu/2/

var arr =[
    {
    "uid": "1",
    "name": "John Doe"
  },
  {
    "uid": "2",
    "name": "Kate Roe"
  }
];

var newArr = arr.filter(function(e) {
    return e["uid"] == 1;
});

alert(newArr["name"]);

I wanted to create a new array that contains only one object which uid is equal to 1. However, it gives me undefined. What am I doing wrong?

sdvnksv
  • 9,350
  • 18
  • 56
  • 108
  • 1
    Two problems: your `.filter()` callback uses `=` instead of `==` (`=` is for assignment), and the `alert()` call should be `alert(newArr[0].name)` or `alert(newArr[0]["name"])` (either would work). – Pointy Apr 17 '16 at 16:24
  • Although = was a misspelling, the second point is what I was looking for! Thanks! – sdvnksv Apr 17 '16 at 16:28

2 Answers2

3

Here you assign the value:

return e["uid"] = 1;

Use double equals == to check the value for equality:

return e["uid"] == 1;

Note that filter() returns array, not object. Use brackets notation [0] to get first element from an array.

See working snippet below

var arr = [{
    "uid": "1",
    "name": "John Doe"
}, {
    "uid": "2",
    "name": "Kate Roe"
}];

var newArr = arr.filter(function(e) {
    return e["uid"] == 1;
});

alert(newArr[0]["name"]);
isvforall
  • 8,768
  • 6
  • 35
  • 50
1

Using Lodash

_.filter(array, { uid: 1 });
GG.
  • 21,083
  • 14
  • 84
  • 130
Devank
  • 159
  • 2
  • 9