1290 1290 - 17 days ago 6
Javascript Question

How to format multiple JSON objects in an Array

I want to have a JSON object which contains multiple person objects. Is there a better way to format this? What I did below is have a

result
key which would be an array consisting of arrays (which have the JSON person object inside of the inner array).

{
result: [
[
{
"name": "Josh",
"age": 15
}
],

[
{
"name": "Joe",
"age": 16
}
]
]
}


Then in the for loop I do something like this:

var nameArray = result[0];
for (var i = 0; i < numberOfObjectsInJSONObject; i++) {
newNameArray.push(nameArray[i].firstPerson);
}

Answer

No point in having each person object wrapped inside it's own array. Unless there is some other grouping that needs done all you should need is one array that contains all the person objects

result: [

          {
            "name": "Josh",
            "age": 15
          },
          {
            "name": "Joe",
            "age": 16
          }

   ]

This array can be sorted by ages or names, filtered etc