合并具有相同“键”的JSON对象,并使用JavaScript添加其对应的“值”

时间:2019-03-06 06:22:52

标签: javascript json merge key

我有以下要合并的JSON对象:

{
  "Results": [
    {
      "Name": "NAME1",
      "Events": {
        "EVENTTYPE": "Upgrade",
        "STARTDATE": "2019-03-05",
        "ENDDATE": "2019-03-19",
        "EVENT_DESC": "Upgrade to A"
      }
    },        
    {
      "Name": "NAME3",
      "Events": {
        "EVENTTYPE": "Upgrade",
        "STARTDATE": "2019-05-08",
        "ENDDATE": "2019-05-29",
        "EVENT_DESC": "Upgrade to A1"
      }
    },
    {
      "Name": "NAME3",
      "Events": {
        "EVENTTYPE": "Upgrade",
        "STARTDATE": "2019-03-06",
        "ENDDATE": "2019-03-13",
        "EVENT_DESC": "Upgrade to A2"
      }
    }
  ]
}

我想合并这样的东西:

{
  "Results": [
    {
      "Name": "NAME1",
      "Events": {
        "EVENTTYPE": "Upgrade",
        "STARTDATE": "2019-03-05",
        "ENDDATE": "2019-03-19",
        "EVENT_DESC": "Upgrade to A"
      }
    },
    {
      "Name": "NAME3",
      "Events": [
        {
          "EVENTTYPE": "Upgrade",
          "STARTDATE": "2019-05-08",
          "ENDDATE": "2019-05-29",
          "EVENT_DESC": "Upgrade to A1"
        },
        {
          "EVENTTYPE": "Upgrade",
          "STARTDATE": "2019-03-06",
          "ENDDATE": "2019-03-13",
          "EVENT_DESC": "Upgrade to A2"
        }
      ]
    }
  ]
}

键是“名称”,您可以在“名称3”下看到重复的键,如何将重复的键与JavaScript合并并在JavaScript中添加相应的值?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用Array#reduce

var obj = { "Results": [ { "Name": "NAME1", "Events": { "EVENTTYPE": "Upgrade", "STARTDATE": "2019-03-05", "ENDDATE": "2019-03-19", "EVENT_DESC": "Upgrade to A" } },{ "Name": "NAME3", "Events": { "EVENTTYPE": "Upgrade", "STARTDATE": "2019-05-08", "ENDDATE": "2019-05-29", "EVENT_DESC": "Upgrade to A1" } }, { "Name": "NAME3", "Events": { "EVENTTYPE": "Upgrade", "STARTDATE": "2019-03-06", "ENDDATE": "2019-03-13", "EVENT_DESC": "Upgrade to A2" } } ] };

Object.keys(obj).forEach(k=>{
      obj[k] = obj[k].reduce((a,b)=>{
          var ind = a.map(i=>i.Name).indexOf(b.Name)
          if(ind > -1){
            a[ind]['Events'].push(b['Events'])
          }else{
           ar=[];
           ar.push(b['Events'])
           b['Events'] = ar;
           a.push(b)
          }
         return a;
      },[])
});
console.log(obj);