Vincent Miquel
Vincent Miquel

Reputation: 143

How to convert json to tree array in JS?

I would like to convert this json / object to this specific structure below to allow me to use a treeList component.

I've tried to build a recursive function but I didn't find the solution yet. Thanks for your help

const data = {
  parent1: {
    child1: { bar: "1" },
    child2: "2"
  },
  parent2: {
    child1: "1"
  }
}

to

const treeData = [
  {
    title: "parent1",
    key: "parent1",
    children: [
      {
        title: "child1",
        key: "child1",
        children: [{ title: "bar", key: "bar", value: "1" }]
      },
      {
        title: "child2",
        key: "child2",
        value: "2"
      }
    ],
  },
  {
    title: "parent2",
    key: "parent2",
    children: [
      {
        title: "child1",
        key: "child1",
        value: "1"
      }
    ]
  }
]

Upvotes: 3

Views: 5483

Answers (2)

Segan
Segan

Reputation: 496

just share sample, a little different from yours. But it give you a hint with recursive function.

https://jsfiddle.net/segansoft/7bdxmys4/1/

function getNestedChildren(arr, parent) {
  var out = []
  for (var i in arr) {
    if (arr[i].parent == parent) {
      var children = getNestedChildren(arr, arr[i].id)

      if (children.length) {
        arr[i].children = children
      }
      out.push(arr[i])
    }
  }
  return out
}


var flat = [{
    id: 1,
    title: 'hello',
    parent: 0
  },
  {
    id: 2,
    title: 'hello',
    parent: 0
  },
  {
    id: 3,
    title: 'hello',
    parent: 1
  },
  {
    id: 4,
    title: 'hello',
    parent: 3
  },
  {
    id: 5,
    title: 'hello',
    parent: 4
  },
  {
    id: 6,
    title: 'hello',
    parent: 4
  },
  {
    id: 7,
    title: 'hello',
    parent: 3
  },
  {
    id: 8,
    title: 'hello',
    parent: 2
  }
]


var nested = getNestedChildren(flat, 0)

document.write('<pre>' + JSON.stringify(nested, 0, 4) + '</pre>');

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You could take an iterative and recursive approach.

function getNodes(object) {
    return Object
        .entries(object)
        .map(([key, value]) => value && typeof value === 'object'
            ? { title: key, key, children: getNodes(value) }
            : { title: key, key, value }
        );
}

const data = { parent1: { child1: { bar: "1" }, child2: "2" }, parent2: { child1: "1" } },
    result = getNodes(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions