如何使用Javascript基于动态数据合并多个对象

时间:2017-11-21 21:19:41

标签: javascript arrays ecmascript-6

变量数组有多个对象,所以我想基于重复的id合并对象,其他值会分配到商品对象中如何做到这一点?...提前感谢

var array = [
   {
      id:1,
      shopname:'star salon',
      offid: 12,
      offname:'100% discount'
   },
   {
      id:1,
      shopname:'star salon',
      offid: 16,
      offname:'Billing Value discount'
   },
   {
      id:3,
      shopname:'trend beauty',
      offid: 19,
      offname:'Percentage Offer'
   }

 ]

最后输出如下:

  var result = [
  {
    id:1,
    shopname:'star salon',
    offer : [
      {
        offid: 12,
        offname:'100% discount'
      },
      {
        offid: 16,
        offname:'Billing Value discount'
      }
    ]
  },

  {
    id:3,
    shopname:'trend beauty',
    offer : [
       {
          offid: 19,
          offname:'Percentage Offer'
       }
    ]
  }

 ]

1 个答案:

答案 0 :(得分:2)

您可以使用此代码收集普通对象中的项目,并按ID键入,然后从中提取值:



var array = [{id:1,shopname:'star salon',offid: 12,offname:'100% discount'},{id:1,shopname:'star salon',offid: 16,offname:'Billing Value discount'},{id:3,shopname:'trend beauty',offid: 19,offname:'Percentage Offer'}];

var result = Object.values(array.reduce( (acc, {id, shopname, offid, offname}) => {
    acc[id] = acc[id] || { id, shopname, offer: [] };
    acc[id].offer.push({ offid, offname });
    return acc;
}, {}));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }