javascript - 如何使用 javascript 从对象数组中获取所需的数据?
问题描述
我有这样的对象数组
var a = [
{'time' : 1539664755070,'T-1': 23 },
{'time' : 1539665095442,'H-1': 24 },
{'time' : 1539666489560,'T-1': 42 },
{'time' : 1539665095442,'H-1': 27 },
{'time': 1539671682230,'H-1': 40.45,'T-2': 33},
{'time': 1539671682230,'T-2': 30.45,'T-1': 65},
{'time': 1539671682230,'T-2': 42.45,'H-1': 11},
{'time': 1539671682230,'T-1': 50.45,'T-2': 85}
];
我想要这样的数据
data : {
'T-1' : [23,42,50.45],
'T-2' : [33,30.45,85],
'H-1' : [24,27,40.45,11]
}
我如何从给定的数据中获取这些数据?
解决方案
const data = a.reduce((acc, row) => {
// Loop over keys of each row.
Object.keys(row)
// Filter out the "time" keys.
.filter((key) => key !== 'time')
// Collect the values by key, storing them in the accumulator.
.forEach((key) => {
if (typeof acc[key] === 'undefined') {
acc[key] = []
}
acc[key].push(row[key])
})
return acc
}, {})
推荐阅读
- python - 如何在 Python 中将两个数字 9 和 3 作为特殊数字?
- go - 为什么不允许在类型断言之后直接为结构的字段赋值?
- java - 理解 JSON 数组请求有问题?
- netlogo - 同一品种的两个特工
- php - 什么 PHP 代码访问 Iterator 接口相当于一个 foreach 循环?
- mysql - Galera 集群不工作使用 wsrep_sst_method=xtrabackup (-v2) 直到第一次使用 rsync
- php - 无法在具有 laravel 和 Angular 的站点上的 api 请求中动态设置 cookie
- html - 下面的代码中的边距是如何工作的?
- c++ - 如何让我的程序在 C++ 中接受来自用户的不同输入?
- firebase - 在快照的数据上调用了 getter 'length'