[Solved] I want to combine the objects in the array, how should I change them?


One method is to convert array into object, and use productId as key:

const data = [
  {
    productId: 6,
    productName: "pouch",
    productPrice: 29000,
    discountRate: 19,
    optionName: "13inch",
    optionPrice: 0,
    qty: 2,
  },
  {
    productId: 6,
    productName: "pouch",
    productPrice: 29000,
    discountRate: 19,
    optionName: "15inch",
    optionPrice: 1000,
    qty: 1,
  },
  {
    productId: 4,
    productName: "pouch",
    productPrice: 29000,
    discountRate: 19,
    optionName: "15inch",
    optionPrice: 1000,
    qty: 1,
  },
]

const results = Object.values(data.reduce((prev, curr) => {
  if (prev[curr.productId])
  {
    const obj = prev[curr.productId];
    if (!obj.option)
    {
      obj.option = [];
      obj.option.push({optionName: obj.optionName, optionPrice: obj.optionPrice, qty: obj.qty});
      delete obj.optionName;
      delete obj.optionPrice;
      delete obj.qty;
    }
    
    prev[curr.productId].option.push({optionName: curr.optionName, optionPrice: curr.optionPrice, qty: curr.qty});
  }
  else
    prev[curr.productId] = Object.assign({}, curr);

  return prev;
  
}, {}));

console.log(results);

1

solved I want to combine the objects in the array, how should I change them?