简体   繁体   English

从对象数组中查找匹配的对象键

[英]Find matching object keys from an array of objects

Given an array of objects all with the same property names, with javascript how would you create a new object made up of key:value pairs that are found in all the objects of the array?给定一个具有相同属性名称的对象数组,使用 javascript,您将如何创建一个由在数组的所有对象中找到的键:值对组成的新对象?

For example, given:例如,给定:

[
  {
    a: 'foo',
    b: 'bar',
    c: 'zip'
  },
  {
    a: 'urg',
    b: 'bar',
    c: 'zip'
  },
  {
    a: 'foo',
    b: 'bar',
    c: 'zip'
  }
]

Result:结果:

{
  b: 'bar',
  c: 'zip'
}

Start with all the elements of the first item (cloned, because we don't want to change the original data), then remove any key-value pairs that do not show up in the subsequent items:从第一项的所有元素开始(克隆,因为我们不想更改原始数据),然后删除任何未出现在后续项中的键值对:

 const data = [ { a: 'foo', b: 'bar', c: 'zip' }, { a: 'urg', b: 'bar', c: 'zip' }, { a: 'foo', b: 'bar', c: 'zip' } ]; const [first, ...rest] = data; const result = rest.reduce((a, e) => { Object.keys(a).forEach(k => { if (!k in e || e[k] !== a[k]) { delete a[k]; } }); return a; }, {...first}); console.log(result);

Just compare each value in the first object with every other object.只需将第一个对象中的每个值与其他所有对象进行比较。

const [first, ...others] = [
  {
    a: 'foo',
    b: 'bar',
    c: 'zip'
  },
  {
    a: 'urg',
    b: 'bar',
    c: 'zip'
  },
  {
    a: 'foo',
    b: 'bar',
    c: 'zip'
  }
];


for (const [key, value] of Object.entries(first)) {
    for (const object of others) {
        if (object[key] !== value) {
            delete first[key];
        }
    }
}

console.log(first);

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

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