使用JavaScript将嵌套JSON的多层children值合并至父级键
处理嵌套
children键的JSON结构转换问题 我有一个从XML Schema自动生成的大型嵌套JSON对象,其中包含多层嵌套的children键。以下是该结构的代码片段:
{ "attributes" : { "name": "xml" }, "children" : [ { "children": [ { "children" :[ { "attributes":{ "min": 1, "max": 2 }, "children":[1,2,3,4] } ] } ] } ] }
我需要将最内层的有效children节点数组移动到最顶层的父级children键中,同时保留所有数据。目标结构如下:
{ "attributes" : { "name": "xml" }, "children" : [ { "attributes":{ "min": 1, "max": 2 }, "children":[1,2,3,4] } ] }
我尝试了以下代码,但未能实现预期效果:
function mergeChildToParent(jsonObj) { for (const key in jsonObj) { if (jsonObj.hasOwnProperty(key) && typeof jsonObj[key] === "object") { if (jsonObj[key].hasOwnProperty("children") && jsonObj[key].value === key) { // Push child value to parent and delete child jsonObj[key].parentValue = jsonObj[key].value; delete jsonObj[key].value; } mergeChildToParent(jsonObj[key]); // Recurse for nested objects } } return jsonObj; }
正确的JavaScript实现方案
思路
通过递归遍历识别仅包含children属性的嵌套节点,逐层扁平化层级,直到遇到包含attributes等其他属性的有效节点,最终将最深层的有效节点数组替换顶层的children数组。
实现代码
function flattenNestedChildren(obj) { // 递归扁平化单个嵌套节点 function flattenNode(node) { // 若当前节点仅含children属性,继续向下扁平化 while (node.children && Object.keys(node).length === 1) { // 适配示例中单元素的children数组场景 node = node.children[0]; } // 递归处理节点自身的children子元素 if (node.children && Array.isArray(node.children)) { node.children = node.children.map(child => { if (typeof child === 'object' && child !== null) { return flattenNode(child); } return child; }); } return node; } // 处理顶层children数组 if (obj.children && Array.isArray(obj.children)) { obj.children = obj.children.map(child => { if (typeof child === 'object' && child !== null) { return flattenNode(child); } return child; }); } return obj; }
使用示例
// 原始JSON对象 const originalObj = { "attributes" : { "name": "xml" }, "children" : [ { "children": [ { "children" :[ { "attributes":{ "min": 1, "max": 2 }, "children":[1,2,3,4] } ] } ] } ] }; // 转换后得到目标结构 const result = flattenNestedChildren(originalObj); console.log(JSON.stringify(result, null, 2));
说明
- 支持处理顶层
children数组中的多个节点,逐个扁平化嵌套层级 - 遇到包含
attributes等非children属性的节点时停止扁平化,保留完整数据 - 兼容多层嵌套场景,不会丢失任何原始数据
内容的提问来源于stack exchange,提问作者Debaditya Sen
相关产品推荐
相关产品推荐

