过滤对象数组,其中对象中的一个字段为数组

时间:2018-12-17 12:33:29

标签: javascript arrays angular typescript

 data:[
        {
           id:1,
           tags:['TagA','TagB','TagC']
         },
         {
           id:2,
           tags:['TagB','TagD']
         },
         {
            id:3,
            tags:['tagE','tagC']
         }
      ]

filterCondition:{tags:['TagA','TagB']}

Expected Output: [
                   {
                     id:1,
                     tags:['TagA','TagB','TagC']
                   },
                   {
                     id:2,
                     tags:['TagB','TagD']
                   }
                 ]

是否有可能使用过滤器方法在打字稿中实现此目的?    如果标签字段不是数组,但是当它在数组中时,    代码中断。

我尝试过,但是失败了:

   data.filter(o => Object.keys(filterCondition).every(k => filterCondition[k].some(f => o[k] === f)));

2 个答案:

答案 0 :(得分:3)

您可以使用filterincludes

const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];
      
const filterData = tag => data.filter(d => tag.some(t => d.tags.includes(t)));

console.log(filterData(['TagA', 'TagB']));

提到的conditionArray形式的少量编辑:

    let filterArray={tags:['TagA','TagB']}

    const data = [{id:1,tags:['TagA','TagB','TagC']},{id:2,tags:['TagB','TagD']},{id:3,tags:['tagE','tagC']}];

    output= data.filter(o => Object.keys(filterArray).every(d => filterArray[d].some(t => o[d].includes(t))));

答案 1 :(得分:2)

const s = {
  data: [{
      id: 1,
      tags: ['TagA', 'TagB', 'TagC']
    },
    {
      id: 2,
      tags: ['TagB', 'TagD']
    },
    {
      id: 3,
      tags: ['tagE', 'tagC']
    }
  ],
  filterCondition: {
    tags: ['TagA', 'TagB']
  }
};

console.log(s.data.filter(a => s.filterCondition.tags

  .some(s => a.tags.join(',').includes(s))));