Looking for recursively remap the nested array in TypeScript / Javascript. I have an array that has parent and children objects and wants to clone with a blank array with only has children and parentId object key. for Ex.
[{
id: "abc",
name: "Parent Object",
children: [{
id: "def",
name: "Child 1 Object",
parentId: "abc",
children: [{
id: "ghi",
name: "Child 2 Object",
parentId: "def",
children: [{
id: "jkl",
name: "Child 3 Object",
parentId: "ghi",
}]
}]
}]
}]
The above array is in the nested and they have other keys also but I have mentioned id, name, parentId, children
, and there are 8 more keys which I have not mentioned here because of complexity. It should be cloned with only the following object key and the rest of the keys will be deleted in the Clone array (workable keys are id, parentId, children)
It should look like below.
[{
id: "abc",
children: [{
id: "def",
parentId: "abc",
children: [{
id: "ghi",
parentId: "def",
children: [{
id: "jkl",
parentId: "ghi",
}]
}]
}]
}]
You could use recursive approach with map
and a for...in
loop to assign properties only if the value exists.
const data = [{"id":"abc","name":"Parent Object","children":[{"id":"def","name":"Child 1 Object","parentId":"abc","children":[{"id":"ghi","name":"Child 2 Object","parentId":"def","children":[{"id":"jkl","name":"Child 3 Object","parentId":"ghi"}]}]}]}]
const f = data =>
data.map(({ children, id, parentId }) => {
const props = { parentId, id }, o = {}
for (let p in props) if (props[p]) o[p] = props[p]
if (children) o.children = f(children)
return o
})
console.log(f(data))