Jian-tai Cai Jian-tai Cai - 1 month ago 21
Javascript Question

Group by children

i have

json
like

[
{ up: 0, id: 1, name: "男裝", level: 1, children:[] },
{ up: 0, id: 2, name: "女裝", level: 1, children: []},
{ up: 1, id: 3, name: "上衣", level: 2, children: []},
{ up: 2, id: 4, name: "上衣", level: 2, children: []},
{ up: 3, id: 5, name: "T穴", level: 3, children: [] },
{ up: 4, id: 6, name: "襯衫", level: 3, children: []},
]


I want to

{
up: 0,
id: 1,
name: "男裝",
level: 1,
children: [
{
up: 1,
id: 3,
name: "上衣",
level: 2,
children: [{up: 3, id: 5, name: "T穴", level: 3, children: []}]
}]
},

{
up: 0,
id: 2,
name: "女裝",
level: 1,
children: [
{
up: 2,
id: 4,
name: "上衣",
level: 2,
children: [{ up: 4, id: 6, name: "襯衫", level: 3, children: [] }]
}]
}


I tried to group like this, but it didn't work

Answer

You can use forEach() loop and inside you also need to use one recursive function that will search each element that is already added to result and its children until it finds object with id that is == to up value of current object in loop.

var data =  [
  { up: 0, id: 1, name: "男裝", level: 1, children:[] },
  { up: 0, id: 2, name: "女裝", level: 1, children: []},
  { up: 1, id: 3, name: "上衣", level: 2, children: []},
  { up: 2, id: 4, name: "上衣", level: 2, children: []},
  { up: 3, id: 5, name: "T穴", level: 3, children: [] },
  { up: 4, id: 6, name: "襯衫", level: 3, children: []},
];

var result = [];

data.forEach(function(e) {
  if (e.up == 0) {
    result.push(e);
  } else {
    function group(input) {
      input.forEach(function(a) {
        if (a.id == e.up) {
          a.children.push(e);
        } else if (a.children.length) {
          group(a.children);
        }
      })
    }
    group(result)
  }
})

console.log(result)