JavaScript对象匹配键值更新:将对象2匹配值同步到对象1
Hey there, based on your example, you want a function that takes a destination object, a base object (obj1), and an update object (obj2), then copies values from obj2 to the destination only for keys that exist in obj1 — ignoring any new keys in obj2 that aren't present in the base object. Let's break this down and build the solution step by step.
Example Scenario
Your given input:
$scope.obj1 = {"id" : 1, "name" : "java"}; $scope.obj2 = {"id" : 1, "name" : "java4you", "gender" : "male"};After calling
compare(destination, obj1, obj2), the desired output fordestinationis:{"id" : 1, "name" : "java4you"}
Solution Code
Here's a straightforward, easy-to-follow implementation of the compare function:
function compare(destination, obj1, obj2) { // Start by copying all key-value pairs from obj1 into destination Object.assign(destination, obj1); // Loop through every key that exists in the base object (obj1) for (const key of Object.keys(obj1)) { // If obj2 has this key, overwrite the destination's value with obj2's value if (obj2.hasOwnProperty(key)) { destination[key] = obj2[key]; } } return destination; }
How It Works
Let's walk through the logic:
- Step 1: We use
Object.assign(destination, obj1)to initialize the destination with exactly the keys and values fromobj1. This ensures we never include extra keys fromobj2. - Step 2: We iterate over each key in
obj1(usingObject.keys()to get a list of its own enumerable keys). - Step 3: For each key, we check if
obj2has that key (usinghasOwnPropertyto avoid inherited properties from the prototype chain). If it does, we update the destination's value to matchobj2's value.
Usage Example
Test it out with your sample data:
const obj1 = {"id" : 1, "name" : "java"}; const obj2 = {"id" : 1, "name" : "java4you", "gender" : "male"}; const destination = {}; compare(destination, obj1, obj2); console.log(destination); // Output: { id: 1, name: 'java4you' }
Alternative Concise Version (Modern JS)
If you prefer a shorter approach using ES6+ features, you can use Object.fromEntries:
function compare(destination, obj1, obj2) { const updatedPairs = Object.entries(obj1).map(([key, originalValue]) => [key, obj2.hasOwnProperty(key) ? obj2[key] : originalValue] ); Object.assign(destination, Object.fromEntries(updatedPairs)); return destination; }
This converts obj1 into an array of key-value pairs, maps each pair to use obj2's value if available, then converts back to an object and assigns it to the destination.
内容的提问来源于stack exchange,提问作者Java4you

