javascript 将对象转换或包装成数组以获取复杂的 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13812344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:51:04  来源:igfitidea点击:

javascript convert or wrap object into array for complex JSON

javascriptunderscore.js

提问by Kevin

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.programsobject 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.

有没有办法始终将countries.programs对象包装到一个数组中,以便最终输出看起来像这样?我在 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!

谢谢!

回答by Amadan

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).

不是自动的,没有。循环遍历国家,然后country.program = [].concat(country.program)。如果它不是数组,最后一个魔术将包装该值,如果它是,则保持原样。大多。(这将是一个不同但等效的数组)。

EDIT per request:

每个请求编辑

_.each(countries, function(country) {
  country.program = [].concat(country.program);
});

回答by alex

Something like this could work

像这样的东西可以工作

_.each(countries, function(country) { 
          ! _.isArray(country.program) && (country.program = [country.program]);
                  });