javascript - 如何将多个数据数组分组为 1 个数组
问题描述
我期望:
[
{
"country_code": "US",
"data": [3,3,3,3]
},
{
"country_code": "VN",
"data": [1,2,3,5]
}
]
我为每个数组尝试了循环,但结果不是预期的。任何人都可以帮助我。谢谢!!!!
解决方案
array.reduce()
您可以使用and as来实现这一点array.forEach()
:
const data = [
{
time: 1,
country:
[
{ country_code: 'US', order_count: 11 },
{ country_code: 'CN', order_count: 21 },
{ country_code: 'VN', order_count: 31 }
]
},
{
time: 2,
country:
[
{ country_code: 'US', order_count: 12 },
{ country_code: 'CN', order_count: 22 },
{ country_code: 'VN', order_count: 32 }
]
},
{
time: 3,
country:
[
{ country_code: 'US', order_count: 13 },
{ country_code: 'CN', order_count: 23 },
{ country_code: 'VN', order_count: 33 }
]
}
]
const mappedData = data.reduce((mdAcc, obj) => {
obj.country.forEach((country) => {
let obj = mdAcc.find((md) => md.country_code === country.country_code);
if (!obj) {
mdAcc.push({country_code: country.country_code, data: [country.order_count]});
} else {
obj.data.push(country.order_count);
}
})
return mdAcc;
}, []);
推荐阅读
- extjs - Extjs 6.5.3 从记录值绑定小部件列的隐藏属性
- android - 设备锁定时 Altbeacon 库不扫描
- artifactory - 如何使用 Percona 集群设置 Artifactory 集群?
- tensorflow - Tensorflow 检测 API 中 SSD 检测器的灰度输入图像
- batch-file - 为什么我们不能在一个批处理文件中执行 BigQuery 的多个语句?
- java - 我课堂上的错误
- docker - Kubernetes 持久卷和主机路径
- c# - 通过 AR 应用将屏幕截图保存到 Android 图库
- php - 在 PHP 中从创建者的站点验证客户端的脚本
- r - bind_rows 到每组 tibble