简体   繁体   English

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

[英]Javascript - Filter object containing arrays with value from another array

I have a problem implementing filtering for nested data.我在实现嵌套数据过滤时遇到问题。 I have this kind of data from API :我有来自 API 的这种数据:

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

I have to filter them with this array : const data = ['shark', 'horse', 'cow', 'parrot']我必须用这个数组过滤它们: const data = ['shark', 'horse', 'cow', 'parrot']

The result I want to achieve :我想要达到的结果:

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

I have tried :我努力了 :

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

and the result :结果:

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

I still can't achieve the desired outcome, because the items inside array will not be added but replaced.我仍然无法达到预期的结果,因为数组中的项目不会被添加而是被替换。 I'm stuck here.我被困在这里。 Any help will be really appreciated.任何帮助将不胜感激。 Thanks !谢谢 !

First you need to loop your object then filter arrays of animals according to data.首先,您需要循环您的对象,然后根据数据过滤动物数组。

 const animals = { fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'],}; const data = ['shark', 'horse', 'cow', 'parrot']; let filtered = {}; for (var a of Object.keys(animals)) { filtered[a] = animals[a].filter(value => data.includes(value)); } console.log(filtered);

You could rebuild the entries of the object.您可以重建对象的条目。

 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; }

You can use the filter method:您可以使用filter方法:

const fish = animals.fish.filter((animal) => animal === 'shark');
const mammals = animals.mammals.filter((animal) => animal === 'cow' || animal === 'horse');
const birds = animals.birds.filter((animal) => animal === 'parrot');

const filtered = {
  fish, // equals to fish: fish
  mammals, // equals to mammals: mammals
  birds, // equals to birds: birds
};

Note that this is just an example.请注意,这只是一个示例。 You can put your own checks in the callback functions but it should return a boolean.您可以将自己的检查放在回调函数中,但它应该返回一个布尔值。

You can iterate over the object and create a new one with the filtered data您可以迭代对象并使用过滤后的数据创建一个新对象

 const animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] } const data = ['shark', 'horse', 'cow', 'parrot'] const filtered = {}; for ( arr in animals) { filtered[arr] = animals[arr].filter ( x => data.includes(x)) } console.log(filtered)

EDIT if you don't want empty arrays as part of the solution:如果您不希望将空数组作为解决方案的一部分,请编辑:

 const animals = { bugs: ['ant', 'cricket'], fish: ['shark', 'whale', 'tuna'], mammals: ['cow', 'horse', 'sheep'], birds: ['eagle', 'crow', 'parrot'], predators: ['tiger', 'lion'] } const data = ['shark', 'horse', 'cow', 'parrot'] const filtered = {}; let tmp = []; for ( arr in animals) { tmp = animals[arr].filter ( x => data.includes(x)) if (tmp.length > 0) filtered[arr] = tmp } console.log(filtered)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在javascript中从包含数组和值的对象数组创建数组和值对象 - creating an object of arrays and values from an array of objects containing arrays and values in javascript 从另一个数组中过滤 object 的数组,在 javascript 中有多个元素 - filter array of object from another array with multiple elements in javascript 对包含对象数组的 Object 进行过滤和排序,同时保留空 Arrays - Filter and Sort an Object Containing Array of Objects While Retaining Empty Arrays 如何使用另一个数组值过滤数组 - How to filter array with another arrays value 如何在 javascript 中对 arrays object 数组使用过滤器? - how to use filter in javascript for an array of arrays object? 如何从Javascript中的另一个数组值中过滤数组值? - How to filter array value from another array values in Javascript? 从另一个数组中获取相同的值并赋值给 arrays 的 object - Get the same value from another array and assign to object of arrays 遍历包含对象的数组的数组,并在JavaScript / Angular中更新数组 - Loop through an array of arrays containing object, and update the array in JavaScript/Angular 使用javascript es6从包含唯一ID和嵌套数组的多个对象数组中获取公共数据 - Get common data from multiple arrays of object that containing a unique id and nested array using javascript es6 Javascript 滤波器阵列基于另一个阵列 object - Javascript filter array based on another array of object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM