我怎样才能展平我的对象数组:
var mylist = [{
THEMEID: 1,
TITLE: "myTheme1",
PARENTID: 0,
children: [{
ITEMID: 1,
NAME: "myItem1",
THEMEID: 1,
PARENTID: 1,
TITLE: "myItem1"
},
{
THEMEID: 3,
TITLE: "mySubTheme1",
PARENTID: 1,
children: [{
ITEMID: 3,
NAME: "myItem3",
THEMEID: 3,
PARENTID: 2,
TITLE: "myItem3"
}]
}
]
},
{
THEMEID: 2,
TITLE: "myTheme2",
PARENTID: 0,
children: [{
ITEMID: 4,
NAME: "myItem4",
THEMEID: 2,
PARENTID: 1,
TITLE: "myItem4"
}]
},
{
THEMEID: 6,
TITLE: "myTheme3",
PARENTID: 0,
children: [{
THEMEID: 5,
TITLE: "mySubTheme3",
PARENTID: 1,
children: [{
THEMEID: 4,
TITLE: "mySubSubTheme3",
PARENTID: 2,
children: [{
ITEMID: 2,
NAME: "myItem2",
THEMEID: 4,
PARENTID: 3,
TITLE: "myItem2"
}]
}]
}]
}
];
console.log(mylist)

在一个数组中,子项的索引将记录在父数组的children数组中 我怎样才能将我的myList数组展平为这样,通过让子记录在父数组的子数组中记录: 示例:
var myFLaten = [
{THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children:[1,2]},
{ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1"},
{THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children:[3]},
{ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3"}]
console.log(myFLaten)

答案 0 :(得分:1)
您可以将最后一个子引用存储在闭包中并迭代给定的数组。在平面数组中插入新对象时,将使用插入对象的索引进行另一次插入。
var tree = [{ THEMEID: 1, TITLE: "myTheme1", PARENTID: 0, children: [{ ITEMID: 1, NAME: "myItem1", THEMEID: 1, PARENTID: 1, TITLE: "myItem1" }, { THEMEID: 3, TITLE: "mySubTheme1", PARENTID: 1, children: [{ ITEMID: 3, NAME: "myItem3", THEMEID: 3, PARENTID: 2, TITLE: "myItem3" }] }] }, { THEMEID: 2, TITLE: "myTheme2", PARENTID: 0, children: [{ ITEMID: 4, NAME: "myItem4", THEMEID: 2, PARENTID: 1, TITLE: "myItem4" }] }, { THEMEID: 6, TITLE: "myTheme3", PARENTID: 0, children: [{ THEMEID: 5, TITLE: "mySubTheme3", PARENTID: 1, children: [{ THEMEID: 4, TITLE: "mySubSubTheme3", PARENTID: 2, children: [{ ITEMID: 2, NAME: "myItem2", THEMEID: 4, PARENTID: 3, TITLE: "myItem2" }] }] }] }],
flat = tree.reduce(function fn(parent, children) {
return function (r, o) {
var temp = { THEMEID: o.THEMEID, TITLE: o.TITLE, PARENTID: o.PARENTID, parentIndex: parent },
index = r.push(temp) - 1;
if ('ITEMID' in o) {
temp.ITEMID = o.ITEMID;
}
children.push(index);
if (o.children) {
o.children.reduce(fn(index, temp.children = []), r);
}
return r;
};
}(undefined, []), []);
console.log(flat);
.as-console-wrapper { max-height: 100% !important; top: 0; }