What's the best way to query an array in javascript to get just the items from it I want?

后端 未结 7 1151
悲哀的现实
悲哀的现实 2020-12-13 18:48

I have an array like this (with just over 3000 objects instead of the 3 here):

items = [{name:\'charlie\', age:\'16\'}, {name:\'ben\', age:\'18\'}, {name:\'s         


        
7条回答
  •  眼角桃花
    2020-12-13 19:15

    Get matched item and items using find() and filter() method

    If you want first matched single item, use find() method which returns single object.

    If you want all matched , use filter() method which returns array of objects.

    let items = [{name:'charlie', age:'16'}, 
    {name:'ben', age:'18'}, 
    {name:'steve', age:'18'}]
    
    let all = items.filter(item=> item.age==='18')
    console.log(all);
    
    let single = items.find(item=> item.age==='18')
    console.log(single);

提交回复
热议问题