I am trying to map a complex object array document to a single level array. For example
const data = [
{
"id": 1,
"name": "Beauty",
"children": {
"0": {
"id": 5,
"parent_id": 1,
"name": "Dermatology",
"code": "dermatology",
"status": 1,
"updated_at": 1678262275,
"created_at": 1678262275
},
"1": {
"id": 7,
"parent_id": 1,
"name": "Plastic surgery",
"code": "plastic_surgery",
"status": 1,
"updated_at": 1678262275,
"created_at": 1678262275
}
}
},
{
"id": 2,
"name": "Healthiness",
"children": {
"0": {
"id": 11,
"parent_id": 2,
"name": "Ophthalmology",
"code": "ophthalmology",
"status": 1,
"updated_at": 1678262275,
"created_at": 1678262275
},
"1": {
"id": 13,
"parent_id": 2,
"name": "Pediatrics",
"code": "pediatrics",
"status": 1,
"updated_at": 1678262275,
"created_at": 1678262275
},
}
}
]
The objective is to turn the array into something like this regardless of the complexity. Basically, if loop through each item in the array and get children item and add parent_name for them
[
{
"id": 5,
"name": "Dermatology",
"parent_id": 1,
"parent_name": "Beauty"
},
{
"id": 7,
"name": "Plastic surgery",
"parent_id": 1,
"parent_name": "Beauty"
},
{
"id": 11,
"name": "Ophthalmology",
"parent_id": 2,
"parent_name": "Healthiness"
},
{
"id": 13,
"name": "Pediatrics",
"parent_id": 2,
"parent_name": "Healthiness"
},
]
My code here, but result not I expect.
let cusData = data
.map((item) => item.children)
.flat()
.map((child) => {
return {id: child.id, name: child.name, parent_id: child.parent_id}
});
Thank you a lots
data.flatMap(({ children }) => Object.values(children));
This is definitely a duplicate, just looking for the appropriate dupe target.