javascript - 如何用数组值重构reduce
问题描述
我正在尝试清理代码。
selectedGroup.items
看起来像这样(简化):
[
{ szenarien: [{extent: {xmin: 1, xmax: 2, ymin: 3, ymax: 4}}, ...] },
{ extent: {...}] } // Extent has same properties as above
]
下面是我的映射代码。目标:获取多边形集合的最外层点
const coordinateValues = selectedGroup.items.reduce(
//TODO: Make this a bit more readable
(acc, item) => {
// item is a group
if (item.szenarios) {
item.szenarios.map((szenario) => {
acc.xmin.push(szenario.extent.xmin);
acc.xmax.push(szenario.extent.xmax);
acc.ymin.push(szenario.extent.ymin);
acc.ymax.push(szenario.extent.ymax);
});
}
// item is a szenario
else {
acc.xmin.push(item.extent.xmin);
acc.xmax.push(item.extent.xmax);
acc.ymin.push(item.extent.ymin);
acc.ymax.push(item.extent.ymax);
}
return acc;
},
{ xmin: [], xmax: [], ymin: [], ymax: [] }
);
// Prepare an extent with the smallest xmin, ymin and the biggest xmax, ymax to have all szenarios in it
const calculatedGroupExtent: __esri.Extent = new EsriExtent({
xmax: Math.max(...coordinateValues.xmax) + 200,
xmin: Math.min(...coordinateValues.xmin) - 200,
ymax: Math.max(...coordinateValues.ymax) + 200,
ymin: Math.min(...coordinateValues.ymin) - 200,
spatialReference: { wkid: 2056 },
});
显然它不是真正可读的。如果不添加许多“可读性常量”(因此没有改进),我找不到一种简化它的漂亮方法
解决方案
您可以创建一个辅助函数,该函数接受一个szenario
对象并将每个属性推['xmin', 'xmax', 'ymin', 'ymax']
送到适当的数组。然后,在迭代项目时,您只需要测试该项目是否是一个组(在这种情况下您会这样做item.szenarios.forEach(addSzenario)
),否则添加单个 szenario:addSzenario(item.extent)
const props = ['xmin', 'xmax', 'ymin', 'ymax'];
const coordinateValues = Object.fromEntries(
props.map(prop => [prop, []])
);
const addSzenario = (szenario) => {
for (const prop of props) {
coordinateValues[prop].push(szenario[prop]);
}
};
for (const item of selectedGroup.items) {
// item is a group
if (item.szenarios) {
item.szenarios.forEach(addSzenario);
} else {
addSzenario(item.extent);
}
}