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
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With