'How to reformat json as nested json by parent_id
Here is the Json array, Every object has is_parent and parent_id properties, If and object has children objects then it's is_parent property is 1 and vice versa.
let list = [
{id: 4, name: 'dd', is_parent: 1, parent_id: 0},
/**/{id: 5, name: 'ee', is_parent: 0, parent_id: 4},
/**/{id: 6, name: 'ff', is_parent: 1, parent_id: 5},
/**//**/{id: 7, name: 'gg', is_parent: 0, parent_id: 6},
{id: 8, name: 'hh', is_parent: 1, parent_id: 0},
/**/{id: 9, name: 'ii', is_parent: 0, parent_id: 8},
{id: 10, name: 'jj', is_parent: 1, parent_id: 0},
/**/{id: 11, name: 'kk', is_parent: 1, parent_id: 10},
/**//**/{id: 12, name: 'll', is_parent: 1, parent_id: 11},
/**//**//**/{id: 13, name: 'mm', is_parent: 0, parent_id: 12},
],
I want to format above json array as below
let array = [
{
id: 4,
name: 'dd',
is_parent: 1,
parent_id: 0,
children: [
{id: 5, name: 'ee', is_parent: 0, parent_id: 4},
{
id: 6,
name: 'ff',
is_parent: 1,
parent_id: 5,
children: [
{id: 7, name: 'gg', is_parent: 0, parent_id: 6}
]
}
]
},
{
id: 8,
name: 'hh',
is_parent: 1,
parent_id: 0,
children: [
{id: 9, name: 'ii', is_parent: 0, parent_id: 8}
]
},
{
id: 10,
name: 'jj',
is_parent: 1,
parent_id: 0,
children: [
{
id: 11,
name: 'kk',
is_parent: 1,
parent_id: 10,
children: [
{
id: 12,
name: 'll',
is_parent: 1,
parent_id: 11,
children: [
{id: 13, name: 'mm', is_parent: 0, parent_id: 12}
]
}
]
}
]
},
]
I tried to do this by foreach loop inside another foreach loop but it didn't work
Solution 1:[1]
'use strict';
const createDataTree = dataset => {
const hashTable = Object.create(null);
dataset.forEach(aData => hashTable[aData.id] = {...aData, children: []});
const dataTree = [];
dataset.forEach(aData => {
if(aData.parent_id) {
hashTable[aData.parent_id].children.push(hashTable[aData.id]);
}
else {
dataTree.push(hashTable[aData.id]);
}
});
console.log(JSON.stringify(dataTree, null ,4))
return dataTree;
};
const list = [
{id: 4, name: 'dd', is_parent: 1, parent_id: 0},
/**/{id: 5, name: 'ee', is_parent: 0, parent_id: 4},
/**/{id: 6, name: 'ff', is_parent: 1, parent_id: 5},
/**//**/{id: 7, name: 'gg', is_parent: 0, parent_id: 6},
{id: 8, name: 'hh', is_parent: 1, parent_id: 0},
/**/{id: 9, name: 'ii', is_parent: 0, parent_id: 8},
{id: 10, name: 'jj', is_parent: 1, parent_id: 0},
/**/{id: 11, name: 'kk', is_parent: 1, parent_id: 10},
/**//**/{id: 12, name: 'll', is_parent: 1, parent_id: 11},
/**//**//**/{id: 13, name: 'mm', is_parent: 0, parent_id: 12},
];
createDataTree(list);
I have modifed the code and taken example from here . This is really good example and works like a charm
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sohan |