【问题标题】:Laravel merge duplicate object in arrayLaravel 合并数组中的重复对象
【发布时间】:2019-04-10 13:40:24
【问题描述】:

这是我的输出查询:

array = [
   0: {brand: "Samsung", phone_unit: "J7 pro"}
   1: {brand: "Samsung", phone_unit: "S9"}
   2: {brand: "Samsung", phone_unit: "S7"}
   3: {brand: "Iphone", phone_unit: "iphone 6s"}
   4: {brand: "Iphone", phone_unit: "iphone X"}
]

这是我想要发生的事情:

array = [
   0: {
        brand: "Samsung",
        phone_unit: ["J7 pro", "S9", "S7"]
      }
   1: {
        brand: "Iphone",
        phone_unit: ["iphone 6S", "iphone X"]
      }
]

如何使用 map 或在 ES6 javascript 中进行此输出

【问题讨论】:

标签: javascript loops duplicates


【解决方案1】:

您可以通过将数组缩减为按brand 分组的对象,然后调用Object.values 来获得最终数组:

const array = [
   {brand: "Samsung", phone_unit: "J7 pro"},
   {brand: "Samsung", phone_unit: "S9"},
   {brand: "Samsung", phone_unit: "S7"},
   {brand: "Iphone", phone_unit: "iphone 6s"},
   {brand: "Iphone", phone_unit: "iphone X"}
];

const result = Object.values(array.reduce((acc, {brand, phone_unit}) => {
  if (!(brand in acc)) acc[brand] = {brand, phone_unit: [phone_unit]};
  else acc[brand].phone_unit.push(phone_unit);
  return acc;
}, {}));

console.log(result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-15
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2021-11-12
    • 2019-12-20
    相关资源
    最近更新 更多