1

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?

0

1 Answer 1

1

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);

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

Comments

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.