3 回答
TA貢獻2039條經驗 獲得超8個贊
一種可能的解決方案,基于我相信您想要的輸出:
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)
添加回答
舉報
