将值组合到具有相同ID的数组(对于JSON对象)

时间:2018-12-21 23:29:09

标签: javascript json object

加入操作后,我得到具有重复ID值的JSON对象 如何将它们及其关联属性映射到使用javascript

的数组
{
    "id": 1,
    "name": "doc 1",
    "appointmentTime": "2018-12-28T00:00:43"
},

{
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-25T23:00:53"
},
{
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-26T23:00:02"
},
{
    "id": 3,
    "name": "doc3",
    "appointmentTime": null
},

我想要类似的东西

{
    "id": 1,
    "name": "doc1",
    "appointmentTime": ["2018-12-28T00:00:43"]
},
{
        "id": 2,
        "name": "doc 2",
        "appointmentTime": ["2018-12-26T23:00:02","2018-12-26T23:00:02"]
    },
    {
        "id": 3,
        "name": "doc3",
        "appointmentTime": null
    },

3 个答案:

答案 0 :(得分:1)

您将需要reduce功能:

const src = [{
    "id": 1,
    "name": "doc 1",
    "appointmentTime": "2018-12-28T00:00:43"
},

{
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-25T23:00:53"
},
{
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-26T23:00:02"
},
{
    "id": 3,
    "name": "doc3",
    "appointmentTime": null
}]

const result = src.reduce((acc, {id, name, appointmentTime}) => {
  const existing = acc.find(i => i.id === id)
  if (existing) { existing.appointmentTime.push(appointmentTime) } 
  else {acc.push({id, name, appointmentTime: [appointmentTime]})}
  
  return acc
}, [])

console.log(result)

我还使用了destructuring assignment

答案 1 :(得分:1)

> let mergeDuplicates = (arr, uniqueKey, mergeKey) => {
> let hashMap = {}; arr.forEach(item => {
> 
>     if(hashMap[item[uniqueKey]] == null) { item[mergeKey] = [item[mergeKey]]; hashMap[item[uniqueKey]] = item;  }
>     else { hashMap[item[uniqueKey]][mergeKey].push(item[mergeKey]); }

>     let ansArr = [];
>     for(var key in hashMap){
>        ansArr.push(hashMap[key]);
>     }
>     return ansArr;
> 
> })
>
> }
> myarray = mergeDuplicates(myarray, "id", "appointmentTime");

答案 2 :(得分:0)

我会这样:

    //lets say you got your jsonObj already in an Array like:
var myarray = [{
    "id": 1,
    "name": "doc 1",
    "appointmentTime": "2018-12-28T00:00:43"
  },
  {
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-25T23:00:53"
  },
  {
    "id": 2,
    "name": "doc 2",
    "appointmentTime": "2018-12-26T23:00:02"
  },
  {
    "id": 3,
    "name": "doc3",
    "appointmentTime": null
  }
];

//just loop through your data and combine it
for (var i = 0; i < myarray.length; i++) {
  //And loop again for duplicate data
  for (var j = i + 1; j < myarray.length; j++) {
    if (myarray[i].id == myarray[j].id) {
      var tmp = myarray[j].appointmentTime;
      myarray[j].appointmentTime = [];
      myarray[j].appointmentTime.push(tmp);
      myarray[j].appointmentTime.push(myarray[i].appointmentTime);

      myarray[i] = {};
    }
  }
}
console.log(myarray);

此后删除所有空的jsonobj

https://jsfiddle.net/m073qwr6/1/