arrays - 我需要通过迭代子数组来找到最少的计数,并根据父数组以角度分隔为多个数组
问题描述
myData = [
{
id: 'N5604-E',
areas: [
{
test_per_week: 154,
test_per_day: 22,
},
{
test_per_week: 154,
test_per_day: 52,
},
{
test_per_week: 154,
test_per_day: 32,
},
],
},
{
id: 'RSP4-E',
areas: [
{
test_per_week: 154,
test_per_day: 12,
},
{
test_per_week: 154,
test_per_day: 29,
},
],
},
];
我需要test_per_week
在每个区域中获得最小值,并且需要根据 ID 将值存储在数组中
我尝试使用 for 循环和每个循环进行迭代:
for (let i = 0; i < this.data.length; i++) {
this.chartProducts.push(this.data[i].id);
this.capacity[i].areas.forEach((element) => {
this.myData.push(element.test_per_day);
});
}
我坚持如何计算test_per_day
一个 ID 中所有区域的最小计数。
解决方案
这可以使用Array.map()
组合来完成Math.min()
,如下所示:
const result = myData.map(o => ({
id: o.id,
min_per_day: Math.min(...o.areas.map(a => a.test_per_day))
}));
请查看下面的可运行代码片段。
const myData = [{
"id": "N5604-E",
"areas": [
{ "test_per_week": 154, "test_per_day": 22 },
{ "test_per_week": 154, "test_per_day": 52 },
{ "test_per_week": 154, "test_per_day": 32 }
]
},
{
"id": "RSP4-E",
"areas": [
{ "test_per_week": 154, "test_per_day": 12 },
{ "test_per_week": 154, "test_per_day": 29 }
]
}
];
const result = myData.map(o => ({
id: o.id,
min_per_day: Math.min(...o.areas.map(a => a.test_per_day))
}));
console.log(result);