-
largeQ
一种可能的解决方案,基于我相信您想要的输出:const array = [{ "Name": "Test", "Children": [{ "Name": "Id", "Property": "Placeholder", "Children": [{ "Name": "Child Id 1", "Property": "Placeholder", "Children": null }, { "Name": "Child Id 2", "Property": "Placeholder", "Children": [{ "Name": "Child Id 3", "Property": "Placeholder", "Children": null }] }] }]}];const map = (arr) => { return arr ? arr.map(fix) : null;}const fix = (item) => { return { data: { name: item.Name }, children: map(item.Children), };}console.log(map(array))或者按照下面的建议,使用简写:const map = arr => arr ? arr.map(fix) : null;const fix = item => ({ data: { name: item.Name }, children: map(item.Children),});
-
ITMISS
我们可以使用一个基本情况,检查Children属性是否为null,如果是,则递归停止并返回Name:const data = [{"Name": "Test", "Children": [{"Name": "Id","Property": "Placeholder","Children": [{"Name": "Child Id","Property": "Placeholder","Children": null }] }] }];const flattenData = (data) => { return data.map(d => { //Base case, recursion stops here if(!d.Children){ return d.Name; } //Continue recursion return {data: {name: d.Name}, children: flattenData(d.Children) } });}console.log(flattenData(data));
-
HUX布斯
您可以创建一个转换子项的函数。如果孩子还有其他孩子,那么该函数将调用自身来递归地转换它们。const input = [ { "Name": "Test", "Children": [ { "Name": "Id", "Property": "Placeholder", "Children": [ { "Name": "Child Id", "Property": "Placeholder", "Children": null } ] } ] }];const transformChildren = children => children.map(child => ({ name: child.Name, children: child.Children ? transformChildren(child.Children) : null}));const output = input.map(item => ({ data: { name: item.Name, }, children: item.Children ? transformChildren(item.Children) : null}))console.log(output)