【问题标题】:Javascript merge and compose Objects with same IDJavascript合并并组合具有相同ID的对象
【发布时间】:2019-08-02 01:28:27
【问题描述】:

我一直在尝试合并数据并得到这个结果:

data = [{serviceID: 22, quantite: 120, typeConviveId: 6},
       {serviceID: 23, quantite: 240, typeConviveId: 6},
        {serviceID: 24, quantite: 100, typeConviveId: 7},
        {serviceID: 25, quantite: 150, typeConviveId: 7}]  

最后需要什么:

result: [ { "22": "120", "23": "240", "typeConviveId": "6"},
        { "24": "100", "25": "150", "typeConviveId": "7" } ] 

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 您是否需要一个通用的 case 函数,或者那些是您将永远拥有的唯一字段? (serviceIDquantitetypeConviveId
  • 家庭优先,可能不在同一个子午线,抱歉

标签: javascript merge


【解决方案1】:

您可以使用数组reduce & 在回调函数中使用findIndex 来获取具有相同typeConviveId 的对象。 findIndex 将从acc 表示的累加器数组中返回具有相同findIndex 的对象的索引。在fiindIndex 中为 -1 然后使用所需的键创建一个新对象并将其推送到累加器数组中。如果已经存在具有相同typeConviveId 的数组,则只需使用新键更新对象

let data = [{
    serviceID: 22,
    quantite: 120,
    typeConviveId: 6
  },
  {
    serviceID: 23,
    quantite: 240,
    typeConviveId: 6
  },
  {
    serviceID: 24,
    quantite: 100,
    typeConviveId: 7
  },
  {
    serviceID: 25,
    quantite: 150,
    typeConviveId: 7
  },
  {
    serviceID: 25,
    quantite: 250,
    typeConviveId: 7
  }
]


let newData = data.reduce(function(acc, curr) {
  let findIndex = acc.findIndex(function(item) {
    return item.typeConviveId === curr.typeConviveId;
  })
  if (findIndex === -1) {
    acc.push({
      typeConviveId: curr.typeConviveId,
      [curr.serviceID]: curr.quantite

    })

  } else {
    acc[findIndex][curr.serviceID] = curr.quantite

  }



  return acc;


}, []);

console.log(newData)

预期结果有问题。如果存在重复键,例如假设 22 这样的键是重复的,那么它将具有最后一个值。

{
        serviceID: 25,
        quantite: 150,
        typeConviveId: 7
      },
      {
        serviceID: 25,
        quantite: 250,
        typeConviveId: 7
      }

在这种情况下,serviceID 在两个对象中都是 25,所以它的值将是 250。它不会有两个具有不同值的键

【讨论】:

  • 感谢您的准确回答 brk!没有重复键,结果很好
【解决方案2】:

您可以使用Array.prototype.mapArray.prototype.filterArray.prototype.reduce 的组合,以及使用Set[...new Set(data.map(x=>x.typeConviveId))] 进行重复数据删除的唯一typeConviveId 列表:

const data = [{serviceID: 22, quantite: 120, typeConviveId: 6}, {serviceID: 23, quantite: 240, typeConviveId: 6}, {serviceID: 24, quantite: 100, typeConviveId: 7}, {serviceID: 25, quantite: 150, typeConviveId: 7}];

const result = [...new Set(data.map(x => x.typeConviveId))].map(
  id => data
  .filter(x => x.typeConviveId === id)
  .reduce((acc, val) => {
    return { ...acc,
      [val.serviceID]: '' + val.quantite
    }
  }, {
    typeConviveId: '' + id
  })
);

console.log(result);

【讨论】:

  • 非常感谢 connexo,非常完美!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2017-06-24
  • 1970-01-01
  • 2015-12-16
  • 1970-01-01
相关资源
最近更新 更多