Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update matched key values in two JavaScript objects

My requirement is compare two objects and copy updated values into first object from second object. Ex :

$scope.obj1={"id" : 1, "name" : "java"}
$scope.obj2={"id" : 1, "name" : "java4you", "gender" : "male"}

compare(destination, bj1, obj2);

Destination variable Output:

{"id" : 1, "name" : "java4you"}

The above two objects contains same keys but values are different. I have to compare obj1 and obj2 and update with matched obj2 values

like image 661
Java4you Avatar asked Jul 12 '26 09:07

Java4you


1 Answers

You can create a copy of obj1 using Object.assign() in a new variable, destination and iterate through each key of obj2 using Object.keys() and array#forEach and check if key exists in destination, in case it exists, update the value in destination from the value of obj2

var obj1={"id" : 1, "name" : "java"},
    obj2={"id" : 1, "name" : "java4you", "gender" : "male"}

var updateObjectValue = (obj1, obj2) => {
  var destination = Object.assign({}, obj1);
  Object.keys(obj2).forEach(k => {
    if(k in destination) {
      destination[k] = obj2[k];
    }
  });
  return destination;
}
console.log(updateObjectValue(obj1, obj2));
like image 148
Hassan Imam Avatar answered Jul 15 '26 00:07

Hassan Imam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!