简体   繁体   中英

Javascript return array from array of objects where property value matches

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

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) 

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM