After filtering the data, I am getting below response inside findChildrens
function.
Now i am expecting is if this.newRegion
have object length more than 1,
than it will merge children of second object inside the parent object children.
For ex - In below Response, i am getting two objects "Africa" and "Europe"
, So i wanted to merge children of "Europe"
inside the parent children of "Africa".
Can anyone please help me to push as my expected output.
findChildrens(){
this.newRegion = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
};
};
Expected Output
this.newRegion = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
},
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
};
CodePudding user response:
Are you looking to do something like
let newRegion = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
let result=newRegion[0];
if(newRegion.length>1){
result.children=result.children.concat(newRegion.slice(1).map(obj=>obj.children).flat())
}
console.log(result)
CodePudding user response:
This function might be what you're looking. But I have to warn you that what you're trying to do is not scalable or representative of code best practices. You might want to edit this code a bit to make it works regardless of how many regions you have.
// It might be preferable to store this in a constant
const REGIONS = [
{
"name": "Africa",
"children": [
{
"name": "Test1",
"region": "1UL Africa"
},
{
"name": "Test2",
"region": "South Africa",
},
{
"name": "Test3",
"region": "New Test",
}
]
},
{
"name": "Europe",
"children": [
{
"name": "Test4",
"region": "1UL Africa"
},
{
"name": "Test5",
"region": "Test Europe"
}
]
}
];
findChildren() {
if (Object.keys(REGIONS).length > 1) {
const mergedChildren = REGIONS[0].children.concat(REGIONS[1].children);
return ({
...REGIONS[0],
children: mergedChildren
})
} else {
return REGIONS[0];
}
}