我使用两个reduce
es和map
从嵌套对象数组中提取一些数据,这个数据正在运行,但它有点难看。如何优化?
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));

如何优化此功能以获得相同的结果?使用一个reduce
代替两个......或其他一些最佳方式。
答案 0 :(得分:1)
您可以移除if (childrenlist) {
并使用预过滤器。
function extractSchools(schools) {
let schoolData = [];
if (schools) {
schoolData = schools
.filter(data => data.children)
.reduce((parentdata, chlrn) => {
const childrendata = chlrn.children.reduce(
(addrsslist, school) =>
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));
答案 1 :(得分:1)
试试这个,结果与你期望的结果没什么不同,但这将是一个更通用的方式,你将获得有关学校的地址。
schools.map(p => {
return {[p.parent]: p.children.map(c => c.address.map(add => add.school))}
})
[
{
"Thomas Jefferson": [
[
"School A"
],
[
"School B"
]
]
},
{
"Jack Chan": [
[
"School C"
]
]
}
]