[英]Convert object with nested objects into array of objects,re- groupped by inner object's keys
[英]Convert Nested Object into Array of Objects and remove keys
如何轉換這樣的對象:
const data =
{
"1":{
name: 'Main Parent',
descendants: {
"1":{
name: "Main Child 1",
children: {
"1":{
name: "Sub Child 1"
}
}
},
"2":{
name: "Main Child 2",
children: {
"1":{
name: "Sub Child 1"
}
}
},
}
}
}
刪除對象鍵,然后轉換為對象數組,如下所示:
const data = [
{
name: 'Main Parent 1',
descendants: [
{
name: "Main Child 1",
children: [
{
name: "Sub Child 1"
}
]
},
{
name: "Main Child 2",
children: [
{
name: "Sub Child 1"
}
]
}
]
}
]
使用lodash _.values()函數進行了嘗試,我可以獲取對象的值,但是對於嵌套對象卻很難。 有任何想法嗎?
使用遞歸和測試兩個children
鍵和descendants
鍵:
const input = { "1": { name: 'Main Parent', descendants: { "1": { name: "Main Child 1", children: { "1": { name: "Sub Child 1" } } }, "2": { name: "Main Child 2", children: { "1": { name: "Sub Child 1" } } }, } } }; const output = recursiveTransform(input); function recursiveTransform(inputObj) { const newArr = Object.values(inputObj); newArr.forEach(obj => { if (obj.descendants) obj.descendants = recursiveTransform(obj.descendants); if (obj.children) obj.children = recursiveTransform(obj.children); }); return newArr; } console.log(output);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.