0

I have a dataset which uses the same _id for two different objects and repeats this in the entire file. How do I go through the list of objects, find the two objects that have a matching _id and merge them into one object?

[    
   {
      "_id": "591323037ca83d48eac1ff31",
      "sessionStartTime": "2017-05-09T23:10:40.000Z",
      "sessionEndTime": "2017-05-10T07:28:40.000Z",
      "timeSessionMinutes": 212,
    },
    {
      "_id": "591323037ca83d48eac1ff31",
      "eventSummary": "Working",
      "eventActivity": "Work",
      "eventStart": "2017-05-09T10:00:00+02:00",
      "eventEnd": "2017-05-09T17:00:00+02:00"
    },
    {
      "_id": "5917165b3ffac25462193490",
      "sessionStartTime": "2017-05-12T22:06:09.000Z",
      "sessionEndTime": "2017-05-13T06:12:09.000Z",
      "timeSessionMinutes": 322,
    },
    {
      "_id": "5917165b3ffac25462193490",
      "eventSummary": "Traveling back home",
      "eventActivity": "Travel",
      "eventStart": "2017-05-09T17:00:00+02:00",
      "eventEnd": "2017-05-09T17:30:00+02:00"
    },
    ...
]

Sorry if already answered, could not find a solution for this specific use case.

1

1 Answer 1

1

An alternative is using the function reduce to group the objects by _id and the function Object.values to extract the grouped objects.

let arr = [   {      "_id": "591323037ca83d48eac1ff31",      "sessionStartTime": "2017-05-09T23:10:40.000Z",      "sessionEndTime": "2017-05-10T07:28:40.000Z",      "timeSessionMinutes": 212,    },    {      "_id": "591323037ca83d48eac1ff31",      "eventSummary": "Working",      "eventActivity": "Work",      "eventStart": "2017-05-09T10:00:00+02:00",      "eventEnd": "2017-05-09T17:00:00+02:00"    },    {      "_id": "5917165b3ffac25462193490",      "sessionStartTime": "2017-05-12T22:06:09.000Z",      "sessionEndTime": "2017-05-13T06:12:09.000Z",      "timeSessionMinutes": 322,    },    {      "_id": "5917165b3ffac25462193490",      "eventSummary": "Traveling back home",      "eventActivity": "Travel",      "eventStart": "2017-05-09T17:00:00+02:00",      "eventEnd": "2017-05-09T17:30:00+02:00"    }],
    result = Object.values(arr.reduce((a, c) => {
      Object.assign((a[c['_id']] || (a[c['_id']] = Object.create(null))), c);
      return a;
    }, Object.create(null)));

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, works perfectly!
@Samsoedien you're welcome! (:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.