梦里花落0921
分配和返回必须不同let parents_children = parents.map(item => { item.children = data. filter(stop => stop.parent == item.ID); return item;});// 更好的性能let result = data2.reduce((map, cur) => { if (cur.parent === "0") { // parent map[cur.ID] = map[cur.ID] || { children: [] }; map[cur.ID] = { ...map[cur.ID], ...cur }; } else { if (!map[cur.parent]) map[cur.parent] = { children: [] }; map[cur.parent].children.push(cur); } return map;}, {});let finalResult = [];for (const key in result) { finalResult.push(result[key]);}console.log(JSON.stringify(finalResult, null, 4));工作样本:const data = [ { ID: 1, parent: "0", title: "Test-1" }, { ID: 2, parent: "1", title: "Test-1-1" }, { ID: 3, parent: "0", title: "Test-2" }, { ID: 4, parent: "0", title: "Test-3" }, { ID: 5, parent: "4", title: "Test-3-1" }, { ID: 6, parent: "4", title: "Test-3-2" }];let parents = data.filter(item => item.parent == "0");let parents_children = parents.map(item => { // create new object return { ...item, children : data.filter(stop => stop.parent == item.ID) };});console.log(JSON.stringify(parents_children, null, 4));console.log(data);const data2 = [ { ID: 1, parent: "0", title: "Test-1" }, { ID: 2, parent: "1", title: "Test-1-1" }, { ID: 3, parent: "0", title: "Test-2" }, { ID: 4, parent: "0", title: "Test-3" }, { ID: 5, parent: "4", title: "Test-3-1" }, { ID: 6, parent: "4", title: "Test-3-2" }];// Better performancelet result = data2.reduce((map, cur) => { if (cur.parent === "0") { // parent map[cur.ID] = map[cur.ID] || { children: [] }; map[cur.ID] = { ...map[cur.ID], ...cur }; } else { if (!map[cur.parent]) map[cur.parent] = { children: [] }; map[cur.parent].children.push(cur); } return map;}, {});let finalResult = [];for (const key in result) { finalResult.push(result[key]);}console.log(JSON.stringify(finalResult, null, 4));.as-console-row {color: blue!important}