简体   繁体   中英

Build a tree from a flat array

I was faced with the question of building a tree from a flat array. We have an array.

[
    {
        "h1": "h001",
        "h2": "z001"
    },
    {
        "h1": "h002",
        "h2": "z002"
    },
    {
        "h1": "h003",
        "h2": "z003"
    }
]

I would like to get something like this:

[{
    "h1": "h001",
    "h2": "z001",
    "children": {
        "h1": "h002",
        "h2": "z002",
        "children": {
            "h1": "h003",
            "h2": "z003"
        }
    }
}]

Is there a way to implement this?

Thanks!

This would be a great place to use the array map() method. Essentially, we'll takin a shallow copy of the array using slice() , then reverse() it, then make each object a property of the previous object's under the children property. When we are done, we re- reverse() the array to get the original order and take the first item.

 let values = [{ "h1": "h001", "h2": "z001" }, { "h1": "h002", "h2": "z002" }, { "h1": "h003", "h2": "z003" }]; let newValues = values.slice().reverse().map((e,i,a) => i? (a[i] = {...e, children: a[i-1] }): a[i]).reverse()[0]; console.log(newValues);

This outputs:

{
  "h1": "h001",
  "h2": "z001",
  "children": {
    "h1": "h002",
    "h2": "z002",
    "children": {
      "h1": "h003",
      "h2": "z003"
    }
  }
}

Iterate by there index and add next node to the previous index.

Implementation:

 const nodes = [{ "h1": "h001", "h2": "z001" }, { "h1": "h002", "h2": "z002" }, { "h1": "h003", "h2": "z003" }]; for (let i = 1; i < nodes.length; i++) { nodes[i - 1].children = nodes[i]; } console.log('solutionByIndex', nodes[0]);

You can use recursion:

 function to_tree(vals){ var v = vals.shift() return vals.length? {...v, children:to_tree(vals)}: v } var vals = [{ "h1": "h001", "h2": "z001" }, { "h1": "h002", "h2": "z002" }, { "h1": "h003", "h2": "z003" }]; console.log([to_tree(vals)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM