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

使用Play Scala合并嵌套JSON:按指定规则合并对象

Merging JSON Objects by Matching Key and Summing Values

Hey there! Great question. Unfortunately, JavaScript doesn’t have a built-in method that directly handles this specific merge scenario—where you match objects by a specific key (c in your case) and sum the values of another property (d). But creating a custom function to do this is straightforward, and I’ll show you how to implement it step by step.

Approach

The core idea is:

  1. Collect all objects from both arrays, grouping them by the c key.
  2. For each group, sum up the d values of all objects in that group.
  3. Convert the grouped data back into the array structure you need, then nest it back into the original object hierarchy.

Custom Implementation

First, let’s build a reusable function that handles the array merging and summing:

function mergeByKeyAndSum(arr1, arr2, matchKey, sumKey) {
  // Use a Map to track cumulative sums for each matchKey value
  const valueMap = new Map();

  // Process the first array
  arr1.forEach(item => {
    const key = item[matchKey];
    valueMap.set(key, (valueMap.get(key) || 0) + item[sumKey]);
  });

  // Process the second array
  arr2.forEach(item => {
    const key = item[matchKey];
    valueMap.set(key, (valueMap.get(key) || 0) + item[sumKey]);
  });

  // Convert the Map back to an array of objects in your desired format
  return Array.from(valueMap.entries()).map(([key, total]) => ({
    [matchKey]: key,
    [sumKey]: total
  }));
}

Example 1: Matching Keys in Both Arrays

Let’s test this with your first set of JSON objects:

const json1 = {a: {b: [{c: "x" , d: 1}, {c: "y" , d: 2}]} };
const json2 = {a: {b: [{c: "x" , d: 3}, {c: "y" , d: 4}]} };

const mergedResult = {
  a: {
    b: mergeByKeyAndSum(json1.a.b, json2.a.b, 'c', 'd')
  }
};

console.log(mergedResult);
// Output: { a: { b: [ { c: 'x', d: 4 }, { c: 'y', d: 6 } ] } }

Example 2: Partial Matching with New Keys

Now let’s use your second scenario where json2 has a mix of existing and new keys:

const json2v2 = {a: {b: [{c: "y" , d: 3}, {c: "z" , d: 4}]} };

const mergedResult2 = {
  a: {
    b: mergeByKeyAndSum(json1.a.b, json2v2.a.b, 'c', 'd')
  }
};

console.log(mergedResult2);
// Output: { a: { b: [ { c: 'x', d: 1 }, { c: 'y', d: 5 }, { c: 'z', d: 4 } ] } }

Notes

  • This function is flexible: you can reuse it for different key names (just pass different matchKey and sumKey arguments).
  • If your JSON structure has deeper nesting, you can extend this logic with recursion to handle multiple levels, but for the structure you provided, this implementation works perfectly.

内容的提问来源于stack exchange,提问作者Monika

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:02:12