【问题标题】:How to merge duplicated Json objects into one?如何将重复的 Json 对象合并为一个?
【发布时间】:2018-03-26 19:31:53
【问题描述】:

我有我的json,如下所示

[{
    "attributeId": 6,
    "attributeType": "price",
    "attributeValue": "{10,20,100}",
    "displayOn": "true",
    "attributeName": "price"
  },
  {
    "attributeId": 6,
    "attributeType": "price",
    "attributeName": "price",
    "displayOn": "true",
    "attributeValue": "{21,40,200}"
  }
]

我想合并成一个不重复的像

[{
  "attributeId": 6,
  "attributeType": "price",
  "attributeValue": "{10,20,100}",
  "displayOn": "true",
  "attributeName": "price",
  "attributeValue": "{21,40,200}"
}]

我尝试了extendconcat 函数。但是,我无法找出正确的方法来做到这一点。请帮我解决这个问题。

【问题讨论】:

  • JSON 是否总是有一个包含两个“对象”的数组?
  • 不..它也会有两个以上

标签: arrays json arraylist


【解决方案1】:

只要您希望数组中较晚的对象覆盖数组中较早的对象值,您可以reduce 数组并将每个旧对象复制到新对象中:

var arr = [{...}, {...}];

var merged = arr.reduce(function(a,b) {
    for (var key in a) {
        a[key] = b[key];
    }
    return a;
});

使用 ES6 语法和特性已大大清除了这一点:

let arr = [{...}, {...}];

let merged = arr.reduce((a, b) => Object.assign(b, a));

请注意,在您的示例中,数组实体不是 JSON 字符串,而是解析的对象。如果您首先需要将 JSON 字符串解析为对象,则需要在减少数组之前执行此操作。

也不是说一个对象不能有两次相同的属性键,就像attributeValue 一样。如果需要保留此值,则需要使用其他方法。

【讨论】:

    猜你喜欢
    • 2016-02-25
    • 2017-12-13
    • 2018-05-24
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多