skip to Main Content

I’m writing a code where I’ve got a nested family tree and I want to create a JSON array with the same. Currently, I can get a parent value in the newly created JSON, but I’m looking for a way to get the ancestor Id.

Here is my code.enter code here

const myObj = {
  id: 1,
  children: [
    {
      id: 2,
      children: [
        {
          id: 3,
        },
      ],
    },
    {
      id: 4,
      children: [
        {
          id: 5,
          children: [
            {
              id: 6,
              children: [
                {
                  id: 7,
                },
              ],
            },
          ],
        },
      ],
    },
  ],
};

idArray = [];

function func(obj, parent) {
  idArray.push({
    id: obj.id,
    name: `${obj.id} ${parent ? `child of ${parent}` : ""}`,
    parentId: parent
  });
  if (!obj.children) {
    return;
  }
  obj.children.forEach((child) => func(child, obj.id));
}

func(myObj);
console.log(idArray);

Here under the parent I want a new key grandparent that shows the grandparent id. please lemme know how I can get this. And, also Is there a way that I can get the result without using a global variable and by just looping over data and returning the final array? like console.log(JSON.stringify(func(myObj))).

Thanks

2

Answers


  1. Generally, if you want to keep track of more than 1 ancestor, a B-Tree is an ideal way of managing that. It is much easier to find the parent of any node on any level.

    Here is a resource where you can learn more about B-Trees. Building a B-Tree in JavaScript

    Login or Signup to reply.
  2. You should check and operate every children on child.
    If a child have children then you must recall same function.

    See ‘finder’ function below.

    const myObj = {
      id: 1,
      name: '11',
      children: [...]
    };
    
    const finder = function (child, tempArray, parentId = 0){
        tempArray.push({id:child.id, name: child.name, parentId });
    
        if(child.children)
        {
            child.children.forEach(grandChild => finder(grandChild,tempArray,child.id)); // here is trick
        }
    }
    
    const fixer = function(firstObject){
        let idArray = [];
        finder(firstObject,idArray);
        return idArray;
    }
    
    const newArray = fixer(myObj);
    console.log(newArray);
    

    output

    [
      { id: 1, name: '11', parentId: 0 },
      { id: 2, name: '22', parentId: 1 },
      { id: 3, name: '33', parentId: 2 },
      { id: 4, name: '44', parentId: 1 },
      { id: 5, name: '55', parentId: 4 },
      { id: 6, name: '66', parentId: 5 },
      { id: 7, name: '77', parentId: 6 }
    ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search