javascript - 如何从嵌套树结构中分离单个对象
问题描述
我有这样的结构
var arr = [
{
"text": "Parent 1",
"id" : "1",
"nodes": [
{
"text": "Child 1",
"id" : "2",
"parentid" : "1",
"nodes": [
{
"text": "Grandchild 1",
"id" : "4",
"parentid" : "2",
},
{
"text": "Grandchild 2",
"id" : "8",
"parentid" : "2",
}
]
},
{
"text": "Child 2",
"id" : "10",
"parentid" : "1",
}
]
},
{
"text": "Parent 2",
"id" : "19",
//no parent id
}
];
我想像这样转换-
var arr=[
{
"text":"text1",
"id" :"1",
//no parent id
},
{
"text":"text2",
"id" :"2",
"idParent":"1"
},
{
"text":"text3",
"id" :"3",
"idParent":"2"
},
{
"text":"text4",
"id" :"4",
"idParent":"1"
},
{
"text":"text5",
"id" :"5",
//no parent id
},
];
我怎样才能在 Javascript 中做到这一点?我想将嵌套树对象转换为单个对象。我不确定如何通过对象数组递归传递以获取单个对象。
在此先感谢您的帮助。
解决方案
您可以使用recursion
:
const arr = [ { "text": "Parent 1", "id" : "1", "nodes": [ { "text": "Child 1", "id" : "2", "parentid" : "1", "nodes": [ { "text": "Grandchild 1", "id" : "4", "parentid" : "2", }, { "text": "Grandchild 2", "id" : "8", "parentid" : "2", } ] }, { "text": "Child 2", "id" : "10", "parentid" : "1", } ] }, { "text": "Parent 2", "id" : "19", }];
const getFlatData=arr=>arr.flatMap(({nodes, ...rest})=>nodes ?
[{...rest}, ...getFlatData(nodes)] : ({...rest}));
console.log(getFlatData(arr));