5

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!

2
  • How are you making your JSON? Or do you want to convert the member to an array only when you are accessing it? 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. Commented Dec 11, 2012 at 1:58

2 Answers 2

19

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not sure what you mean. Could you type out how this would work?
Good call with [].concat(...)! That was the functionality I was searching for. Cheers.
2

Something like this could work

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

2 Comments

This one worked for me, but JSLint throws this error: Error: Problem at line 24 character 79: Expected an assignment or function call and instead saw an expression. ! _.isArray(country.program) && (country.program = [country.program...
@Kevin: It is a style complaint; the program should still work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.