如何对对象数组进行分组并转换重复项

How to groupBy an Array of Objects and convert the duplicates

大家好,我有这个数据结构,我需要分组,如果有任何重复项将这两个对象转换成一行..

数据结构

var shipTo = [
  { addressLine1: "address 1", name: "Jeff" },
  { addressLine1: "address 2", name: "Taylor" },
  { addressLine1: "address 1", name: "Megan" },
  { addressLine1: "address 3", name: "Madison" },
];

分组函数

function groupArrayOfObjects(list, key) {
  return list.reduce(function (rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
}

我已经通过地址

上面的这个函数对地址属性进行了分组
const groupedAddress = groupArrayOfObjects(shipTo, "addressLine1");

我的新数据结构是

我的最终结果是这样的:

Shipping Address for Shipment 1 & 3 is "address 1"

Shipping Address for Shipment 2 is "address 2"

reduce可以将当前数组元素的索引作为第3个参数。然后你可以将它传递给你的累加器并且在最终数组中可以用它做你想做的事

var shipTo = [
  { addressLine1: "address 1", name: "Jeff" },
  { addressLine1: "address 2", name: "Taylor" },
  { addressLine1: "address 1", name: "Megan" },
  { addressLine1: "address 3", name: "Madison" },
];

function groupArrayOfObjects(list, key) {
  return list.reduce(function (rv, x, idx) {
    (rv[x[key]] = rv[x[key]] || []).push({...x, index:idx+1});
    return rv;
  }, {});
}

const groupedAddress = groupArrayOfObjects(shipTo, "addressLine1");
console.log(groupedAddress)


//for completeness
Object.values(groupedAddress).forEach((address) => {
    let addressName = address[0].addressLine1
  let joinedIndices = address.map(({index}) => index).join(" & ")
  console.log(`Shipping Address for Shipment ${joinedIndices} is "${addressName}"`)
})