Home > Net >  Find matching object keys from an array of objects
Find matching object keys from an array of objects

Time:06-06

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?

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

CodePudding user response:

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

CodePudding user response:

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);
  • Related