Prem Prem - 2 months ago 21
JSON Question

How to convert a non-nested json to nested (normalized) one using node.js

I'm looking-out for any npm modules that can convert non-nested json to nested one. For example, I have a json as follows:

[
{
event : 'xyz'
time: '2016-01-01'
},
{
event: 'xyz'
time: '2016-01-02'
},
{
event : 'xyz'
time: '2016-01-03'
},
{
studentid: 'xyz'
time: '2016-01-04'
}
]


I want this json object to be nested/normalized/embedded as follows:

{
event: 'xyz',
{
time : ['2016-01-01', '2016-01-02', '2016-01-03', '2016-01-04']
}
}

Answer

What you actually need in your example is to group by event field

You can use for example lodash groupBy method for this purpose.