I have a JSON that looks something like this:
var countries = [
{
name: 'united states',
program: {
name: 'usprogram'
}
},
{
name: 'mexico',
program: {
name: 'mexico program'
}
},
{
name: 'panama',
program: [
{
name: 'panama program1'
},
{
name: 'panama program2'
}
]
},
{
name: 'canada'
}
];
Is there a way to ALWAYS wrap the countries.programs
object into an array such that the final output looks something like this? I tried some of the utility functions in underscoreJS, but the solution has eluded me.
var countries = [
{
name: 'united states',
program: [ //need to wrap this object into an array
{
name: 'usprogram'
}
]
},
{
name: 'mexico',
program: [ //need to wrap this object into an array
{
name: 'mexico program'
}
]
},
{
name: 'panama',
program: [
{
name: 'panama program1'
},
{
name: 'panama program2'
}
]
},
{
name: 'canada'
}
];
Thanks!
Not automatic, no. Loop through the countries, then country.program = [].concat(country.program)
. This last piece of magic will wrap the value if it is not an array, and leave it as-is if it is. Mostly. (It will be a different, but equivalent array).
EDIT per request:
_.each(countries, function(country) {
country.program = [].concat(country.program);
});
Something like this could work
_.each(countries, function(country) {
! _.isArray(country.program) && (country.program = [country.program]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With