Nick Medvik
Nick Medvik

Reputation: 13

convert nested object in parent / children structure js

I try to convert this structure (each child is property in object):

const tree = {
  "Parent 1" : {
    "Children1": {
      "Children2": {
          "#1": { info: {}},
          "#2": { info: {}}.
          "#3": { info: {}}
    },
    "Children1-1": {
      "Children2-2": {
          "#1": { info: {}},
          "#2": { info: {}}.
          "#3": { info: {}}
    }
  },
  "Parent 2": {
  ...
   }
};

In to this tree structure with parent child view. But in the end of my tree i don't need childrens

const resultTeee = [
  {
    name: 'Parent 1',
    children: [
      {
        name: 'Children 1',
        children: [
          {
            name: 'Children 2',
            children: [
              {name: "#1", info: {}},
              {name: "#2", info: {}}
            ]
          }
        ]
      },
      {
        name: 'Children 1-1',
        children: [
          {
            name: 'Children 2-2',
            children: [
              {name: "#1", info: {}},
              {name: "#2", info: {}}
            ]
          }
        ]
      }
    ]
  },
  {
    name: 'Parent 2'
    ....
  }
]

I try "traverse tree" approach but can't understand how to switch for new children path. Object can have multiple nested structure on each level.

Upvotes: 0

Views: 539

Answers (1)

NebSehemvi
NebSehemvi

Reputation: 33

const toArrayTree = (obj) => {
    return Object.keys(obj).map(key => {
        return {name: key, children: [toArrayTree(obj[key])]}
    })
}

object for testing

const tree = {
    "Parent 1" : {
        "Children1": {
            "Children2": {
                "#1": { info: {}},
                "#2": { info: {}},
                "#3": { info: {}},
            }
        },
    },
    "Parent 2" : {
        "Children2.1": {
            "Children2.2": {
                "#4": { info: {}},
                "#5": { info: {}},
                "#6": { info: {}},
            }
        },
    },
};

But as @adiga said, why the last branch of tree is not { name: 'info', children: [] }?

Update on solution

const toArrayTree = (obj) => {
    return Object.keys(obj).map(key => {
        return typeof obj[key] === 'object' ?
            {name: key, children: [toArrayTree(obj[key])]} :
            {name: key, [key]: obj[key]};
    })
}

It's really bad idea to use Object(v) === v, because it would be true for v being function for example

Upvotes: 1

Related Questions