1

I have a collection of string literals in an array

var selected = ['a', 'b.c', 'b.c.d', 'b.c.d.e'];

How can I create a below JSON tree structure using JavaScript? Any help would be appreciable.

[{
    "title": "a",
    "id": "a"
  },
  {
    "title": "b",
    "id": "b",
    "children": [{
      "title": "c",
      "id": "c",
      "children": [{
          "title": "d",
          "id": "d",
          "children": [{
            "title": "e",
            "id": "e"
          }]
        },
        {
          "title": "f",
          "id": "f"
        }
      ]
    }]
  }
]
2
  • Where are you getting the initial object from, it might be easier to change the way the data is returned rather than trying to manipulate the result. Commented Jan 13, 2020 at 10:40
  • you dont have any "f" in your original array... Commented Jan 13, 2020 at 10:51

1 Answer 1

2

Using recursion

var selected = ['a', 'b.c', 'b.c.d', 'b.c.d.e', 'b.c.g'];
var result = {};

selected.forEach(i =>
  i.split('.').reduce((result, val) => result[val] = result[val] || {}, result)
)

function toTree(o) {
  return Object.entries(o).map(([k, v]) => {
    let r = {'title': k, 'id': k, 'children': toTree(v)}
    !r.children.length && delete r.children
    return r
  })
}
result = toTree(result)

console.log(result)

Sign up to request clarification or add additional context in comments.

3 Comments

Well, i found one more issue with this solution. If i have 2 children for an attribute then it does not work. var selected = ['a', 'b.c', 'b.c.d', 'b.c.d.e', b.c.g]; In this case "c" should have 2 children (i.e [d,g]). But it is overwriting with the latest value. Kindly help.
@SaktiDash you can check the updated answer. I just check for available value result[val] || {}
Could you please help me on this query. stackoverflow.com/questions/59882169/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.