[英]javascript convert or wrap object into array for complex JSON
I have a JSON that looks something like this: 我有一个看起来像这样的JSON:
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? 有没有一种办法总是包裹countries.programs
对象到一个数组,使得最终的输出看起来是这样的? I tried some of the utility functions in underscoreJS, but the solution has eluded me. 我在underscoreJS中尝试了一些实用程序功能,但是解决方案使我难以理解。
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)
. 循环浏览国家/地区,然后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]);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.