Chan
Chan

Reputation: 43

Convert Nested Object into Array of Objects and remove keys

How do I convert an Object like this:

const data = 
{
  "1":{
    name: 'Main Parent',
    descendants: {
      "1":{
        name: "Main Child 1",
        children: {
          "1":{
            name: "Sub Child 1"
          }
        }
      },
      "2":{
        name: "Main Child 2",
        children: {
          "1":{
            name: "Sub Child 1"
          }
        }
      },

    }
  }
}

to remove the object keys then convert to array of objects like this:

const data = [
  {
    name: 'Main Parent 1',
    descendants: [
      {
        name: "Main Child 1",
        children: [
          {
            name: "Sub Child 1"
          }
        ]
      },
      {
        name: "Main Child 2",
        children: [
          {
            name: "Sub Child 1"
          }
        ]
      }
    ]
  }
]

Tried using lodash _.values() function and I can get the values of the objects but having trouble on doing it for nested objects . Any Ideas?

Upvotes: 1

Views: 525

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

Use recursion and test for both children keys and descendants keys:

const input = {
  "1": {
    name: 'Main Parent',
    descendants: {
      "1": {
        name: "Main Child 1",
        children: {
          "1": {
            name: "Sub Child 1"
          }
        }
      },
      "2": {
        name: "Main Child 2",
        children: {
          "1": {
            name: "Sub Child 1"
          }
        }
      },

    }
  }
};

const output = recursiveTransform(input);
function recursiveTransform(inputObj) {
  const newArr = Object.values(inputObj);
  newArr.forEach(obj => {
    if (obj.descendants) obj.descendants = recursiveTransform(obj.descendants);
    if (obj.children) obj.children = recursiveTransform(obj.children);
  });
  return newArr;
}
console.log(output);

Upvotes: 1

Related Questions