3
I have the following array:
let exemplo = [{
alarm: {
title: "Pai",
id: "1"
},
children: [],
parent: "",
}, {
alarm: {
title: "Filho",
id: "2",
},
parent: "Pai",
children: [],
}, {
alarm: {
title: "Neto",
id: "3",
},
parent: "Pai",
children: [],
}, {
alarm: {
title: "Filho 2",
id: "4",
},
parent: "Pai",
children: [],
}, {
alarm: {
title: "Neto 2",
id: "5",
},
parent: "Filho",
children: [],
}, {
alarm: {
title: "Pai 2",
id: "6",
},
parent: "",
children: [],
}, {
alarm: {
title: "Filho 2.2",
id: "6",
},
parent: "Pai 2",
children: [],
}];
How can I turn him recursively in an array of objects based on the condition that a larm must be the son of a Alarm Parent?
I tried to use the function below but was unsuccessful:
public getNestedChildren(arr, parent) {
var out = [];
for (var i in arr) {
if (arr[i].parent === parent) {
console.log(arr[i].alarm.parent);
var children = getNestedChildren(arr, arr[i]);
if (children.length) {
arr[i].children = children;
}
out.push(arr[i]);
}
}
return out;
}
var nest = this.getNestedChildren(exemplo, '');
The expected exit would be something like:
let exemplo = [
{
alarm: {
title: "Pai",
id: "1"
},
parent: "",
children: [
{
alarm: {
title: "Filho",
id: "2",
},
parent: "Pai",
children: [
{
alarm: {
title: "Neto",
id: "3",
},
parent: "Filho",
children: [],
}
]
}
]
}
Always obeying this hierarchy, father, son, grandson, etc., regardless of the amount of alarms.
What is the expected output?
– Costamilam
I updated the question
– haykou
You used the
for()
to iterate your list, but it is in invalid format, I believe you want to use theforeach
because its structure is similar to that of the foreach loop.– Robson Silva
Possible duplicate of How to modify an object array through a condition?
– José Guilherme Oliveira