[英]How filter in a nested tree object without losing structure in javascript?
[英]How to separate individual object from nested tree structure
我有这样的结构
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 中执行此操作? 我想从嵌套树 object 转换为单个对象。 我不确定如何通过对象数组递归传递以获取单个对象。
在此先感谢您的帮助。
您可以使用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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.