Vahlk Vahlk - 4 months ago 8
Node.js Question

Merging Objects with Like Terms

I am currently attempting to group together a data set by various characteristics. I am at the last part of my exercise and that is:

Turn this:

[
{
"AU": {
"iOS": 1
}
},
{
"US": {
"iOS": 2
}
},
{
"CA": {
"iOS": 1
}
},
{
"US": {
"Android": 1
}
},
{
"DO": {
"Android": 1
}
}
]


into this:

[
{
"AU": {
"iOS": 1
}
},
{
"US": {
"iOS": 2,
"Android": 1
}
},
{
"CA": {
"iOS": 1
}
},
{
"DO": {
"Android": 1
}
}
]


In other words, groupBy CountryCode and keep respective iOS or Android tags. Also, keep in mind, no computed keys are allowed. Computed Keys Any help would be much appreciated.

Answer

In totally vanilla JavaScript -

input.forEach(function(item){
    Object.keys(item).forEach(function(country){
        var systems = item[country]
        if (!obj[country]) obj[country] = {}
        Object.keys(systems).forEach(function(system){
            if (!obj[country][system]) obj[country][system] = item[country][system]
            else obj[country][system] += item[country][system]
        })
    })
})

If you can use a library (such an Underscore or JQuery) you could tighten up the syntax too

Comments