简体   繁体   English

如何比较嵌套的对象数组并仅返回公共值

[英]How to compare a nested array of objects and only return common values

I have a nested array of objects which contains some duplicate values:我有一个嵌套的对象数组,其中包含一些重复值:

[
  [
    {
      name: 'name1',
      email: 'email1'
    },
    {
      name: 'name2',
      email: 'email2'
    }
  ],
  [
    {
      name: 'name1',
      email: 'email1'
    }
  ],
  [
    {
      name: 'name1',
      email: 'email1'
    },
    {
      name: 'name2',
      email: 'email2'
    }
  ]
]

I want to create a new single array from this data containing only the objects that exist in all the nested arrays:我想从此数据创建一个新的单个数组,其中仅包含所有嵌套 arrays 中存在的对象:

[
  {
    name: 'name1',
    email: 'email1'
  }
]

I have tried the following code:我尝试了以下代码:

const filteredArray = arrays.shift().filter(function (v) {
  return arrays.every(function (a) {
    return a.indexOf(v) !== -1;
  });
});
console.log('filteredArray => ', filteredArray);

and:和:

const filteredArray = arrays.reduce((p,c) => p.filter(e => c.includes(e)));
console.log('filteredArray => ', filteredArray);

However these both only return an empty array.但是,它们都只返回一个空数组。

Would really appreciate any help.非常感谢任何帮助。 TIA TIA

You could create a Map with objects from the first subarray, keyed by their JSON representation (after ordering their keys).您可以使用来自第一个子数组的对象创建一个 Map,由它们的 JSON 表示(在订购它们的键之后)键控。 Then filter the next subarray for objects whose JSON representation is in that map, and put those in a new map.然后为 JSON 表示在 map 中的对象过滤下一个子数组,并将它们放入新的 map 中。 Continue like that for all subarrays.对所有子数组继续这样。 Finally return the values that remain in the last map:最后返回最后一个 map 中剩余的值:

 // Helper functions: const str = o => JSON.stringify(Object.keys(o).sort().map(key => [key, o[key]])); const mapify = arr => new Map(arr.map(o => [str(o), o])); const intersection = data =>.data?length: []. [...data.slice(1),reduce((map. arr) => mapify(arr.filter(o => map,get(str(o)))). mapify(data[0]));values()]: const data = [[{name, 'name1':email, 'email1'}:{name, 'name2':email, 'email2'}]:[{name, 'name1':email, 'email1'}]:[{name, 'name1':email, 'email1'}:{name, 'name2':email. 'email2'}]] console;log(intersection(data));

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM