如何将JSON中子对象的value求和并添加至对应父对象?
Got it, let's tackle this problem head-on. You need to compute the sum of all child value fields and attach that sum as a new value property to each parent node in your hierarchical JSON structure. Recursion is perfect here because it naturally handles nested data—no matter how deep the hierarchy goes.
JavaScript 实现方案
First, here's a recursive function that will process your data:
function calculateParentValues(node) { // 如果当前节点有子节点,递归处理每个子节点并累加总和 if (node.children) { let totalValue = 0; node.children.forEach(child => { totalValue += calculateParentValues(child); }); // 给当前父节点添加value属性,值为所有子节点的value总和 node.value = totalValue; return totalValue; } else { // 底层节点(无children)直接返回自身的value,供父节点求和 return node.value; } }
使用示例
Apply this function to your original data:
// 你的原始JSON数据 const originalData = [{ "name": "minpur", "children": [{ "name": "ppp1", "children": [{ "name": "feeder", "children": [{ "name": "rmu16", "children": [{ "name": "invt16", "children": [ { "aname": "inv 01", "value": 300 }, { "aname": "inv 03", "value": 500 } ] }] }] }] }] }]; // 处理每个顶级节点(这里只有一个) originalData.forEach(node => calculateParentValues(node)); // 输出处理后的结果 console.log(JSON.stringify(originalData, null, 2));
This will output exactly the structure you want, with every parent node having a value property equal to the sum of all its descendant values.
Python 实现方案
If you're working with Python instead, the logic is identical—just translated to Python syntax:
def calculate_parent_values(node): if 'children' in node: total_value = 0 for child in node['children']: total_value += calculate_parent_values(child) node['value'] = total_value return total_value else: return node['value'] # 原始数据 original_data = [{ "name": "minpur", "children": [{ "name": "ppp1", "children": [{ "name": "feeder", "children": [{ "name": "rmu16", "children": [{ "name": "invt16", "children": [ { "aname": "inv 01", "value": 300 }, { "aname": "inv 03", "value": 500 } ] }] }] }] }] }] # 处理数据 for node in original_data: calculate_parent_values(node) # 打印结果 import json print(json.dumps(original_data, indent=2))
工作原理
The recursive function works by:
- Checking if the current node has
children(or'children'in Python). - If it does, iterate over each child, recursively call the function on the child, and add the returned value to a running total.
- Assign that total to the current node's
valueproperty and return it to the parent node above. - If the node has no children (the bottom level with
anameandvalue), just return its ownvalueto be included in the parent's sum.
This approach scales perfectly even if your hierarchy gets deeper or has more branches—no need to adjust the code for different levels.
内容的提问来源于stack exchange,提问作者Ram

