按其中一个元素对对象数组进行分组

Group an array of objects by one of its elements

我有一个看起来像这样的对象数组

arr = [{
  group: "Forest",
  value: "81.8",
  year: 2015
}, {
  group: "Forest",
  value: "86.4",
  year: 2016
}, {
  group: "Forest",
  value: "67.3",
  year: 2017
}, {
  group: "Forest",
  value: "70.8",
  year: 2018
}, {
  group: "Forest",
  value: "67.6",
  year: 2019
}, {
  group: "Mountain",
  value: "78.6",
  year: 2015
}, {
  group: "Mountain",
  value: "83.1",
  year: 2016
}, {
  group: "Mountain",
  value: "65.6",
  year: 2017
}, {
  group: "Mountain",
  value: "68.1",
  year: 2018
}, {
  group: "Mountain",
  value: "63.7",
  year: 2019
}];

有没有办法按组对这个数组进行分组?我想创建类似这样的东西:

arr = [{
    group: "Forest",
    val2015: 81.8,
    val2016: 86.4,
    val2017: 67.3,
    val2018: 70.8,
    val2019: 67.6
},{
    group: "Mountain",
    val2015: 78.6,
    val2016: 83.1,
    val2017: 65.6,
    val2018: 68.1,
    val2019: 63.7
}];

是否可以用 js 做到这一点,或者我可以将 arr 发送到 ajax 然后用 php 然后 return 做到这一点?

您可以创建一个 Map 以通过组字符串对组进行键控,并将这些键关联到普通对象,每个对象都具有组 属性。

然后迭代数据以通过 year/value 组合填充这些对象。

最后从地图中提取这些对象:

const arr = [{group: "Forest",value: "81.8",year: 2015}, {group: "Forest",value: "86.4",year: 2016}, {group: "Forest",value: "67.3",year: 2017}, {group: "Forest",value: "70.8",year: 2018}, {group: "Forest",value: "67.6",year: 2019}, {group: "Mountain",value: "78.6",year: 2015}, {group: "Mountain",value: "83.1",year: 2016}, {group: "Mountain",value: "65.6",year: 2017}, {group: "Mountain",value: "68.1",year: 2018}, {group: "Mountain",value: "63.7",year: 2019}];

const groups = new Map(arr.map(({group}) => [group, { group }]));
for (const {group, value, year} of arr) {
    groups.get(group)["val" + year] = +value;
}
const result = [...groups.values()];

console.log(result);