You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript对象匹配键值更新:将对象2匹配值同步到对象1

Update Matching Key Values from a Second Object to the First in JavaScript

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 for destination is:

{"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 from obj1. This ensures we never include extra keys from obj2.
  • Step 2: We iterate over each key in obj1 (using Object.keys() to get a list of its own enumerable keys).
  • Step 3: For each key, we check if obj2 has that key (using hasOwnProperty to avoid inherited properties from the prototype chain). If it does, we update the destination's value to match obj2'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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:19:11