我在实现嵌套数据过滤时遇到问题.我从API获得了此类数据:

  const animals = {
    bugs: ['ant', 'cricket'],
    fish: ['shark', 'whale', 'tuna'],
    mammals: ['cow', 'horse', 'sheep'],
    birds: ['eagle', 'crow', 'parrot'],
    predators: ['tiger', 'lion']
  }

我必须使用此数组过滤它们:

我想要达到的结果是:

const filtered = {
    fish: ['shark'],
    mammals: ['cow', 'horse'],
    birds: ['parrot'],
}

我try 过:

filter.forEach((item) => {
      for (let key in animals) {
        let species = []
        if (animals[key].includes(item)) {
          filtered[key] = [...species, species]
        }
      }
    })

结果是:

const filtered = {
      fish: ['whale'],
      mammals: ['cow',],
      birds: ['parrot'],
    }

我仍然无法达到预期的效果,因为数组中的项目不会被添加,而是被替换.我被困在这里了.任何帮助都将不胜感激.谢谢

推荐答案

您可以重建对象的条目.

const
    animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] },
    data = ['shark', 'horse', 'cow', 'parrot'],
    result = Object.fromEntries(Object
        .entries(animals)
        .flatMap(([k, a]) => {
            a = a.filter(v => data.includes(v));
            return a.length
                ? [[k, a]]
                : []
        })
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Javascript相关问答推荐

如何在react js中显示文本字段或2个不同的组件?

在JavaScript中使用setProperty方法试图修改css元素值时,我遇到错误

文件阅读器未读取一个文件

订阅操作顺序

如何在JavaScript中在文本内容中添加新行

成帧器运动中的运动组件为何以收件箱开始?

硬币兑换运行超时

react—router v6:路由没有路径

仅针对RTK查询中的未经授权的错误取消maxRetries

为什么!逗号和空格不会作为输出返回,如果它在参数上?

处理时间和字符串时MySQL表中显示的日期无效

在Matter.js中添加从点A到另一个约束的约束

第三方包不需要NODE_MODULES文件夹就可以工作吗?

在数组中查找重叠对象并仅返回那些重叠对象

Angular 形式,从DOM中删除不会删除指定索引处的内容,但会删除最后一项

当我try 将值更改为True时,按钮不会锁定

Google脚本数组映射函数横向输出

在Odoo中如何以编程方式在POS中添加产品

在Java脚本中录制视频后看不到曲目

如何在Java脚本中并行运行for或任意循环的每次迭代