create csv from objects with different keys

Viewed 52

I have an array of objects. Some of their keys are identical but some of them exist only in one of the object:

const data =[
{id:123, name:foo, number:25},
{id:124, name:boo, number:35, blue:8},
{id:125, name:soo, number:40, red:10}
]

I want to convert my data into a CSV, so that the headers will include all keys. if key doesn't exists in the object its value should be null , see example below:

id name number blue red
123 foo 25 null null
124 boo 35 8 null
125 soo 40 null 10

I was able to achieve this with few loops , but the code is ugly :)

Thanks!

1 Answers
Related