Home > Net >  compare two array of objects keys, original array should mutate in javascript
compare two array of objects keys, original array should mutate in javascript

Time:12-07

How can we compare two array of objects on the basis of their keys or properties of object in javaScript?

for an example:

 let result1 = [
      { a: 10, b: 20, c: 22 },
      { a: 20, b: 33, c: 11 },
    ];
    let result2 = [
      { a: 10, b: 20 },
      { a: 20, b: 33 },
    ];

 result1.filter(function (obj) {
      return !result2.some(function (obj2) {
        let key1 = Object.keys(obj);
        let key2 = Object.keys(obj2);
        key1?.forEach((x, index1) => {
          key2?.forEach((y, index2) => {
            console.log(index1, index2)
            if (x === y) {
              return obj[x] === obj2[y];
            }
          });
        });
      });
    });

console.log(result1)

output: current output

expected output:

result1 =
     [
      { a: 10, b: 20 },
      { a: 20, b: 33 },
    ];

CodePudding user response:

let result1 = [
  { a: 10, b: 20, c: 22 },
  { a: 20, b: 33, c: 11 },
];
let result2 = [
  { a: 10, b: 20 },
  { a: 20, b: 33 },
];
let temp = []
result1.map(function(obj) {
  return !result2.some(function(obj2) {
    let key1 = Object.keys(obj);
    let key2 = Object.keys(obj2);
    key1.forEach((x) => {
      key2.forEach((y) => {
        if (x === y) {
          obj[x] === obj2[y] ? temp.push({
            [x]: obj[x]
          }) : null;
        }
      })
    });
  })
})
console.log(temp);

try this code

You are getting the result1 array back beacause the array is not getting filtered.

The filter function is not getting anything from returned as the first foreach loop is not returning and the some function is also not returning anything

Now you can use map function instead of filter as the function is not returning anything

CodePudding user response:

I just try this solution in a different way, We can also achieve this requirement by doing deep copy of original array and then mutate it using forEach().

Live Demo :

let result1 = [
  { a: 10, b: 20, c: 22 },
  { a: 20, b: 33, c: 11 }
];

let result2 = [
  { a: 10, b: 20 },
  { a: 20, b: 33 }
];

const clone = structuredClone(result1);

clone.forEach((obj, index) => {
    result1[index] = {};
  Object.keys(result2[index]).forEach(key => {
    result1[index][key] = obj[key]
  });
});

console.log(result1);

  • Related