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!
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!
Share Improve this question asked Dec 11, 2012 at 1:43 KevinKevin 3,6317 gold badges37 silver badges41 bronze badges 2- How are you making your JSON? Or do you want to convert the member to an array only when you are accessing it? – Sampson Commented Dec 11, 2012 at 1:50
- 3 That's not JSON, that is Javascript objects and arrays. JSON is a text format to represent objects and arrays. – Guffa Commented Dec 11, 2012 at 1:58
2 Answers
Reset to default 19Not 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]);
});