【发布时间】:2021-03-10 05:58:09
【问题描述】:
我有这样的结构
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 中做到这一点?我想将嵌套树对象转换为单个对象。我不知道如何递归传递对象数组以获取单个对象。
提前感谢您的帮助。
【问题讨论】:
-
创建一个新数组A。对于Array中的所有对象,将对象添加到A并检查如果对象有节点,然后再次调用该方法以获得节点。不要忘记删除对象上的节点。
标签: javascript node.js arrays json object