如何使用javascript从对象数组中获取所需数据?

时间:2018-11-16 12:05:02

标签: javascript angular angular5

我有这样的对象数组

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]
}

如何从给定数据中获取此数据?

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这是一个解决方案,如果不清楚,请让我知道:

#!/bin/bash

while [ $# -gt 0 ]; do
  case "$1" in
    -path=*)
      directory="${1#*=}"
      ;;
    *)
      echo "Invalid args: $@"
      exit 1
  esac
  shift
done

# You can do whatever with $directory here

答案 2 :(得分:0)

您可以将array#reduceObject.values()一起使用,以创建密钥的哈希并添加与之对应的值。然后使用Object.assign()spread syntax创建最终对象。

let data = [ {'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} ],
  result = Object.assign({}, ...Object.values(data.reduce((r, o) => {
    let keys = Object.keys(o).filter(k => k !== 'time');
    keys.forEach(key => {
      r[key] = r[key] || {[key] : []};
      r[key][key].push(o[key]);
    });
    return r;
  },{})));
console.log(result);

答案 3 :(得分:0)

使用Map代替Key,Value数组的最佳用例。简化了很多事情。