3 回答
TA贡献2039条经验 获得超7个赞
一种可能的解决方案,基于我相信您想要的输出:
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),
});
TA贡献1871条经验 获得超8个赞
我们可以使用一个基本情况,检查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));
TA贡献1876条经验 获得超6个赞
您可以创建一个转换子项的函数。如果孩子还有其他孩子,那么该函数将调用自身来递归地转换它们。
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)
添加回答
举报