Reputation: 23
Assuming my current object is this below:
{
"name": 1
"type": 2
"kind": 2
}
I want to print all the objects in the array that have the same "type" as my current object, which is 2
.
[
{
"name": 1
"type": 2
"kind": 3
},
{
"name": 2
"type": 2
"kind": 1
},
{
"name": 2
"type": 1
"kind": 3
}
]
EXPECTED OUTPUT:
[
{
"name": 1
"type": 2
"kind": 3
},
{
"name": 2
"type": 2
"kind": 1
}
]
Upvotes: 1
Views: 738
Reputation: 2420
To get the objects which has some particular value for a property from an array can be achieved using Array.filter()
method. Use it like this:
let arr = [
"name": 1,
"type": 2,
"kind": 3
},
{
"name": 2,
"type": 2,
"kind": 1
},
{
"name": 2,
"type": 1,
"kind": 3
}
];
let filteredArr = arr.filter(item => item.type === 2);
The filteredArr
will only have objects whose type is 2.
Hope this helps.
Upvotes: 0
Reputation: 5054
The answer is array filter :
let array = [
{
"name": 1,
"type": 2,
"kind": 3
},
{
"name": 2,
"type": 2,
"kind": 1
},
{
"name": 2,
"type": 1,
"kind": 3
}
]
let customFilteredArray = array.filter(data => data.type===2) //you can add your custom check
Here is example :
Upvotes: 0
Reputation: 3571
Use Array.prototype.filter()
MDN
Like fullArray.filter(element => element.type == myObject.type)
or if you are still using ES5 fullArray.filter(function(element) { return element.type == myObject.type; })
Beware I’m not on a computer, so I can’t test the code.
Upvotes: 3