How do i filter an array inside of a array of objects?

前端 未结 4 843
暗喜
暗喜 2021-02-04 17:58

I\'m trying to filter a list by tags:

const initialState = [
     {id:1 ,name: \'Product A\', image: \'pic-001.jpg\', tags: [\'nature\', \'campi         


        
4条回答
  •  一生所求
    2021-02-04 18:27

    You can create a Set of selected tags, and use Array#some to check if at least one of the tags in the Set exists in the objects' tags list:

    const initialState = [
         {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
         {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
         {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
    ];
    
    const filterByTags = ['nature', 'family'];
    
    const filterByTagSet = new Set(filterByTags);
    
    const result = initialState.filter((o) => 
      o.tags.some((tag) => filterByTagSet.has(tag))
    );
    
    console.log(result);

提交回复
热议问题