Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Given two equal objects, filter only the differences

Lets say I have two different objects

let obj1 = {
  "value1" : "1",
  "value2" : "2",
  "value3" : "3",
  "value4" : "4"
}

let obj2 = {
  "value1" : "1",
  "value2" : "3",
  "value3" : "3",
  "value4" : "5"
}

I need a the differences in a new object that will depend on obj2

result = { "value2":"3" , "value4" : "5" }

The case can be too , that obj1 === undefined
In that case, I need all the values from obj2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Currently I have

let result = {}
let singleChange = false

for (const i of Object.entries(obj2)) {
    if (obj1 && obj1[i[0]] !== i[1]) {
      result [i[0]] = i[1];
      singleChange = true
    } else if(!singleChange) {
      result = obj2;
    }
  }

But it doesnt really sem to work properly all the times. Is there a better way to write this?

>Solution :

A modern version with entries and fromEntries:

let obj1 = {
  "value1" : "1",
  "value2" : "2",
  "value3" : "3",
  "value4" : "4"
}

let obj2 = {
  "value1" : "1",
  "value2" : "3",
  "value3" : "3",
  "value4" : "5"
}

let obj3 = undefined;

function objIntersection(o1, o2) {
  const filteredArray = Object.entries(o2)
  .filter(([k,v]) => o1?.[k] !== v);

  return Object.fromEntries(filteredArray);
}

console.log(objIntersection(obj1, obj2));
console.log(objIntersection(obj3, obj2));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading