【问题标题】:How to filter an object by data from array in JS [duplicate]如何通过JS中的数组中的数据过滤对象[重复]
【发布时间】:2021-10-05 23:59:20
【问题描述】:

我有一个数组

const newChecked = ["recreational", "charity"]

和一个对象

const allActivities = [
  {activity: '...', type: 'social', },
  {activity: '...', type: 'social', },
  {activity: '...', type: 'charity', },
  {activity: '...', type: 'recreational', },
]

我想获得一个新对象,它不包含 newChecked 中包含的类型。换句话说,newActivitiesList 应该包含type"social" 的数据。

const newActivitiesList = allActivities.filter((item) =>
  newChecked.map((i) => {
    return item.type !== i;
  })
);

【问题讨论】:

    标签: javascript arrays dictionary object filter


    【解决方案1】:

    您可以将Array#filterArray#includes 结合使用。

    const newChecked = ["recreational", "charity"]
    const allActivities = [
    {activity: '...', type: 'social', },
    {activity: '...', type: 'social', },
    {activity: '...', type: 'charity', },
    {activity: '...', type: 'recreational', },
    ];
    const res = allActivities.filter(({type})=>!newChecked.includes(type));
    console.log(res);

    【讨论】:

      【解决方案2】:

      您可以使用Array.prototype.reduce函数创建一个新数组

      const newChecked = ["recreational", "charity"]
      
      const allActivities = [
        {activity: '...', type: 'social', },
        {activity: '...', type: 'social', },
        {activity: '...', type: 'charity', },
        {activity: '...', type: 'recreational', },
      ];
      
      const newActivitiesList = allActivities.reduce((accumulator, current) => {
        if(newChecked.indexOf(current.type) === -1) {
          return accumulator.concat(current);
        } else {
          return accumulator;
        }
      },[]);
      
      console.log(newActivitiesList);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-04
        • 2015-12-29
        • 2019-10-30
        • 1970-01-01
        • 2019-07-18
        • 1970-01-01
        • 1970-01-01
        • 2022-12-12
        相关资源
        最近更新 更多