简体   繁体   中英

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

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

Try this,

function compare(obj1, obj2)
{
    let obj = {};
    for(let k in obj1)
    {
         obj[k] = obj2[k];
     }
    return obj;
}

Usage should be like,

var destination = compare(obj1,obj2);

Without actually referring to methods that can be used in angularJs, You can try this:

 function compare(o1, o2) { var biggest = o1; if (Object.keys(o2).length > Object.keys(o1).length) { biggest = o2; } for (let key in biggest) { if (!biggest.hasOwnProperty(key)) continue; if (o1[key] != o2[key]) { console.info("Difference in '"+ key +"': "+ o1[key] +" <> "+ o2[key]); } } } var $scope = {}; $scope.obj1 = {"id" : 1, "name" : "java"}; $scope.obj2 = {"id" : 1, "name" : "java4you", "gender" : "male"}; compare($scope.obj1, $scope.obj2);

But be careful using this, since it has many possible cases to fail.

Using Angularjs, you can use .equal to compare and get the result, I don't see what is not working or providing your code will only gets you the answers.

$scope.result = angular.equals($scope.obj1, $scope.obj2);
if($scope.result === true){    
$scope.obj1 = $scope.obj2;
}

I had to update @Bharadwaj answer for it to work for me.
for (... in ...) statements must be filtered with an if statement

 var obj1={"id" : 1, "name" : "java"}, obj2={"id" : 1, "name" : "java4you", "gender" : "male"}; function compare(obj1, obj2) { let obj = {}; for(let k in obj1) { if(obj1[k] !== obj2[k]) { obj = Object.assign({}, obj1, obj1[k] = obj2[k]); } } return obj; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM