首页 > 解决方案 > 如何使用 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]
}

我如何从给定的数据中获取这些数据?

标签: javascriptangularangular5

解决方案


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
}, {})

推荐阅读