I've come across an array of objects that looks like this
let data = [
{
"id": 1,
"name": "Sam",
"father": true,
"group": "orange"
},
{
"id": 2,
"name": "Alex",
"father": true,
"group": "red"
},
...
];
The goal is to organize the data so that each father has their children listed in an array under a key named "members". The children should have the same color as their fathers. For example:
{
"id": 1,
"name": "Sam",
"father": true,
"group": "orange"
"member":[
{
"id": 6,
"name": "Oliver",
"father": false,
"group": "orange"
}
};
// more examples
I have implemented a solution using nested loops, but it's not very efficient and runs slow due to the complexity. Here is my current code:
function sorting(data) {
data.forEach(fatherObjects => {
if (fatherObjects.father) {
var member = [];
data.forEach(childrenObjects => {
if (!childrenObjects.father && childrenObjects.group === fatherObjects.group) {
member.push(childrenObjects)
}
});
fatherObjects["member"] = member;
console.log(fatherObjects);
}
});
}
sorting(data);
If you have any suggestions on how to make this process more efficient without sacrificing readability, please let me know.