Deka87 Deka87 - 7 months ago 12
Javascript Question

Filter an array of object by object content

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?

Answer

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"]);

Comments