Home > Back-end >  NodeJs How to convert parent-child json array to json-object with key-id and value array of all chil
NodeJs How to convert parent-child json array to json-object with key-id and value array of all chil

Time:01-16

I have a parent-child array that lookes like this:

const myTestArray = [
    {
        "id": "1",
        "parent": "root"
    },
    {
        "id": "2",
        "parent": "1"
    },
    {
        "id": "3",
        "parent": "1"
    },
    {
        "id": "4",
        "parent": "2"
    },
    {
        "id": "5",
        "parent": "4"
    }
];

From this I have been able to create an nested parent-child json-tree, but now I need another data-structure that looks like this:

const childesArray = {

    "1": ["1", "2", "3", "4", "5"],
    "2": ["2", "4", "5"],
    "3": ["3"],
    "4": ["4", "5"],
    "5": ["5"]
};

For each element in myTestArray I need an array that contains all childes (deep) for that element.

I guess I also here can use reduce on this array, but I'm stucked right now how I can achive this. Anyone that can point me in the right direction? Or have any solution on this?

Br. Rune

CodePudding user response:

There are several ways to achieve this, but I tried to keep it simple. Take a look at this example.

const nesting = {};

myTestArray.forEach((item) => {
  const { parent, id } = item;

  if (!nesting[id]) {
    nesting[id] = [id];
  }

  if (!nesting[parent] && parent !== "root") {
    nesting[parent] = [parent];
  }

  if (parent !== "root") {
    nesting[parent].push(id);
  }
});

console.log(nesting);
//
//   {
//     "1":["1","2","3"],
//     "2":["2","4"],
//     "3":["3"],
//     "4":["4","5"],
//     "5":["5"]
//    } 
//

CodePudding user response:

You could take the JSON object and iterate through it with a ForEach loop. You can then append an element to the index of its parent, and you would end up with a 2-dimensional array such as the one you specified.

var newArr = {}; 
myTestArray.forEach(e => {
    newArr[e.id] = [e.id]; 
    if(e.parent != "root"){
        newArr[e.parent].push(e.id); 
    }
});

would produce

newArr = { '1': [ '1', '2', '3' ],
  '2': [ '2', '4' ],
  '3': [ '3' ],
  '4': [ '4', '5' ],
  '5': [ '5' ] }
  •  Tags:  
  • Related