将对象数组缩减为唯一键并添加该键共有的值数组

Reduce array of objects to unique keys and add array of values common to that key

我想按 car 对这个数组的值进行分组 键,然后将该车共有的值推送到值数组中。

我设法用这个做到了,但想知道是否有更简单的方法用 reduce 来做到这一点。

const arr = [{
  car: 'audi',
  value: 'black'
}, {
  car: 'audi',
  value: 'expensive'
}, {
  car: 'fiat',
  value: 'red'
}, {
  car: 'fiat',
  value: 'cheap'
}]

// Simple array with unique car
const cars = Array.from(new Set(arr.map(({ car }) => car)))
// Array of objects with unique `car` and an empty `values` array for each
const result = cars.map((car) => ({ car, values: [] }))

// Push to values array the `value` for each car
arr.map((obj) => {
  result.map((res) => {
    if (obj.car === res.car) {
      res.values.push(obj.value)
    }
  })
})

console.log(result)
/*
[{
  car: 'audi',
  values: ['black', 'expensive']
}, {
  car: 'fiat',
  values: ['red', 'cheap']
}]
*/

创建一个由 car 名称索引的对象,然后遍历原始数组,将值推送到对象上的数组:

const arr = [{
  car: 'audi',
  value: 'black'
}, {
  car: 'audi',
  value: 'expensive'
}, {
  car: 'fiat',
  value: 'red'
}, {
  car: 'fiat',
  value: 'cheap'
}];

const carsByName = {};
for (const { car, value } of arr) {
  if (!carsByName[car]) carsByName[car] = { car, value: [] };
  carsByName[car].value.push(value);
}
console.log(Object.values(carsByName));

虽然 可以 reduce 完成,但可以说 not very semantically appropriate 当累加器永远不会改变时(并且在语法上有点嘈杂):

const arr = [{
  car: 'audi',
  value: 'black'
}, {
  car: 'audi',
  value: 'expensive'
}, {
  car: 'fiat',
  value: 'red'
}, {
  car: 'fiat',
  value: 'cheap'
}];

const carsByName = arr.reduce((a, { car, value }) => {
  if (!a[car]) a[car] = { car, value: [] };
  a[car].value.push(value);
  return a;
}, {});
console.log(Object.values(carsByName));

您可以使用 .reduce to group the items by car, and then, .map 创建具有 car 及其 values 的对象列表:

const arr = [{
  car: 'audi',
  value: 'black'
}, {
  car: 'audi',
  value: 'expensive'
}, {
  car: 'fiat',
  value: 'red'
}, {
  car: 'fiat',
  value: 'cheap'
}]

let result = arr.reduce((acc,item) => {
  const values = acc[item.car];
  acc[item.car] = values ? [...values, item.value] : [item.value];
  return acc;
}, {});

result = Object.entries(result).map(([car, values]) => ({car,values}));

console.log(result)

只需使用 reduce 即可。将带有键 carvalues 的汽车数组保存在 acc 中。然后映射它。我的意思是:

const arr = [
  {
    car: "audi",
    value: "black",
  },
  {
    car: "audi",
    value: "expensive",
  },
  {
    car: "fiat",
    value: "red",
  },
  {
    car: "fiat",
    value: "cheap",
  },
];

const result = Object.entries(
  arr.reduce((acc, { car, value }) => {
    if (acc[car]) {
      return {
        ...acc,
        [car]: [...acc[car], value],
      };
    }

    return { ...acc, [car]: [value] };
  }, [])
).map(([car, values]) => ({ car, values }));

console.log(result);