Javascript - 过滤包含数组的对象,其值来自另一个数组

标签 javascript arrays object

我在对嵌套数据实现过滤时遇到问题。我有来自 API 的这种数据:

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

我必须用这个数组过滤它们: const data = ['鲨鱼', '马', '牛', '鹦鹉']

我想要达到的结果:

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

我试过了:

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 - 过滤包含数组的对象,其值来自另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72683502/

相关文章:

javascript - Chrome : not "remembering" the choice to allow access to microphone

javascript - 根据 google places API 调用更新状态

javascript - JQuery-向 anchor 添加属性和参数

Java 将值从数组传递到新对象实例

javascript - fecha.js - 日期/时间,一天中的特定时间

ios - Swift:使用 UISearchController/Predicates 过滤结构数组

arrays - 为什么我不能在 T-SQL 中使用 JSON_ARRAY() 合并 2 行?

c# - 如何分离String数组数据?

在对象之前打印的 C++ 无意义对象

php - 为什么我的 php 数组作为对象保存到 MongoDB,然后作为带有字符串化键的关联数组进行检索?