重新排序对象 - 将对象复制(剪切)到另一个对象中

数据


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 => item.children = data.filter(stop => stop.parent == item.ID));

console.log(parents_children);根本不工作。


console.log(parents);工作正常。但我不明白为什么......let parents_children影响如何let parents?对于我要归档的内容,是否有更好的解决方案?


慕森卡
浏览 100回答 2
2回答

梦里花落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}

繁花如伊

.map()你忘了从我相信回来。尝试以下操作:let parents_children = parents.map(item => {   item.children = data.filter(stop => stop.parent == item.ID)   return item;});我希望这有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript