1

I'm receiving an array of objects saying which events have changed. The following code is an example of such change. There are other fields that could change as well, but they won't appear here.

[{ "eventId": "1", "name": "name_a", "isCancelled": "true"},
{ "eventId": "1", "name": "name_a", "date": "2018-11-17T00:00:00.000Z"},
{ "eventId": "2", "name": "name_b", "Status": "Postponed"},
{ "eventId": "3", "name": "name_c", "isCancelled": "true"},
{ "eventId": "3", "name": "name_c", "status": "Private"}]

Is there a way that I can combine the objects with the same ID? Something similar to this.

[{ "eventId": "1", "name": "name_a", "isCancelled": "true", "date": "2018-11-17T00:00:00.000Z"},
{ "eventId": "2", "name": "name_b", "Status": "Postponed"},
{ "eventId": "3", "name": "name_c", "isCancelled": "true", "status": "Private"}

I've seen a lot of threads and they're mostly focused on combining 2 arrays by matching their IDs.

1 Answers1

3

You can use for .. of like below to loop through every element and then based on event id concat the objects

let arr = [{ "eventId": "1", "name": "name_a", "isCancelled": "true"},
{ "eventId": "1", "name": "name_a", "date": "2018-11-17T00:00:00.000Z"},
{ "eventId": "2", "name": "name_b", "Status": "Postponed"},
{ "eventId": "3", "name": "name_c", "isCancelled": "true"},
{ "eventId": "3", "name": "name_c", "status": "Private"}]

let o = {}
for(let d of arr) {
  o[d['eventId']] = { ...(o[d['eventId']] || {}), ...d }
}

console.log(Object.values(o))
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22
  • Thank you very much! I really hate just copying and pasting it. Any recommendations on what topics of JS to study to get better at problem solving? – Yoel Lorenzo Nov 20 '18 at 12:32
  • Using reduce with Map would probably cleaner. `[ ...arr .reduce( (result, item) => result.set(item.eventId, { ...(result.get(item.eventId) || {}), ...item, }), new Map(), ) .values(), ]` – HMR Nov 20 '18 at 12:35
  • @HMR It's matter of choice I believe. I pick `reduce` and `for...of` interchangeably. Given this problem, I found `for..of` to be cleaner (again personal choice). Reg: use of `new Map()` I personally favour using map where we would need to get rid of duplicates.. Having said that it's again personal decision and we are all correct at the same time. End of the day code must be clean, fast, and readible. Thank you for mentioning though. :) – Nitish Narang Nov 20 '18 at 12:50
  • @YoelLorenzo Hmm.. Firstly, get yourself comfortable with "Array.map", reduce, filter, find, for.. of and solve as many problems as you can. Best way I found is - search questions on stackoverflow - solve yourself and then look for others answers and see how you could have done differently. With time you will get better. :) – Nitish Narang Nov 20 '18 at 12:52
  • 1
    @NitishNarang Thank you very much! I'll try my best. – Yoel Lorenzo Nov 20 '18 at 13:06