Reputation: 3942
Is there a built in Javascript function or library to do the following:
const data = [
{ name: 'name1', type: 'type1' },
{ name: 'name2', type: 'type2' },
{ name: 'name3', type: 'type3' },
{ name: 'name4', type: 'type2' },
];
To search the following and return all objects where type = 'type2'
Something similar to data.findIndex((i) => i.type === 'type2')
but returns all matches rather than first index?
Thanks
Upvotes: 0
Views: 52
Reputation: 36564
You can use filter()
const data = [
{ name: 'name1', type: 'type1' },
{ name: 'name2', type: 'type2' },
{ name: 'name3', type: 'type3' },
{ name: 'name4', type: 'type2' },
];
let res = data.filter(({type}) => type === "type2");
console.log(res)
Upvotes: 1
Reputation: 191976
You are looking for Array.filter()
:
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Example:
const data = [
{ name: 'name1', type: 'type1' },
{ name: 'name2', type: 'type2' },
{ name: 'name3', type: 'type3' },
{ name: 'name4', type: 'type2' },
]
const result = data.filter(o => o.type === 'type2')
console.log(result)
Upvotes: 9