使用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:
- Collect all objects from both arrays, grouping them by the
ckey. - For each group, sum up the
dvalues of all objects in that group. - 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
matchKeyandsumKeyarguments). - 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
相关产品推荐
相关产品推荐

