I am extracting some data out of an array of nested objects, using two reducees, and map, which is working at the moment, but it is a bit ugly. How can this be optimized?
function extractSchools(schools) {
let schoolData = [];
if (schools) {
schoolData = schools.reduce(function(parentdata, chlrn) {
let childrenlist = chlrn.children;
let childrendata = [];
if (childrenlist) {
childrendata = childrenlist.reduce(function(addrsslist, school) {
return addrsslist.concat(school.address.map(i => i.school));
}, []);
}
return parentdata.concat(chlrn.parent, childrendata);
}, []);
}
return {
schoolData
};
}
const schools = [{
"parent": "Thomas Jefferson",
"children": [{
"address": [{
"school": "School A"
}]
},
{
"address": [{
"school": "School B"
}]
}
]
},
{
"parent": "Jack Chan",
"children": [{
"address": [{
"school": "School C"
}]
}]
}
];
console.log(extractSchools(schools));
How can I optimize this function to get the same results? using one reduce instead of two... or some other optimal way of doing it.
parentandchildren. Should they benameandaddresses? Or is there more nesting going on? B) Why is the address an array and is the label nested in an object with aschoolproperty? I think the only way you can simplify the data conversion is by altering the data format to better meet your front-end requirements.