Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript convert or wrap object into array for complex JSON

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!

like image 408
Kevin Avatar asked Dec 11 '12 01:12

Kevin


2 Answers

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);
});
like image 118
Amadan Avatar answered Nov 11 '22 11:11

Amadan


Something like this could work

_.each(countries, function(country) { 
          ! _.isArray(country.program) && (country.program = [country.program]);
                  });
like image 37
alex Avatar answered Nov 11 '22 10:11

alex