In the following JSON object:
var employees = { "accounting" : [   // accounting is an array in employees.
                                { "firstName" : "John",  // First element
                                  "lastName"  : "Doe",
                                  "age"       : 23 },
                                { "firstName" : "Mary",  // Second Element
                                  "lastName"  : "Smith",
                                  "age"       : 32 }
                              ], // End "accounting" array.                                  
              "sales"       : [ // Sales is another array in employees.
                                { "firstName" : "Sally", // First Element
                                  "lastName"  : "Green",
                                  "age"       : 27 },
                                { "firstName" : "Jim",   // Second Element
                                  "lastName"  : "Galley",
                                  "age"       : 41 }
                              ] // End "sales" Array.
            } // End Employees
How do I restructure the object so I can access each employee first name like this:
employees[0].firstName
employees[1].firstName
// etc
                JSON arrays can be of multiple data types. JSON array can store string , number , boolean , object or other array inside JSON array. In JSON array, values must be separated by comma.
{} denote containers, [] denote arrays.
Can JSON have nested objects? Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.
JSON - Syntax Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma). Square brackets hold arrays and values are separated by ,(comma).
It would require restructuring it so that you'd eliminate the "accounting/sales" properties and make employees an Array of Objects.
Example: http://jsfiddle.net/hgMXw/
var employees = [
    {
    "dept": "accounting", // new property for this object
    "firstName": "John",
    // First element
    "lastName": "Doe",
    "age": 23
    },
    {
    "dept": "accounting", // new property for this object
    "firstName": "Mary",
    // Second Element
    "lastName": "Smith",
    "age": 32
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Sally",
    // Third Element
    "lastName": "Green",
    "age": 27
    },
    {
    "dept": "sales", // new property for this object
    "firstName": "Jim",
    // Fourth Element
    "lastName": "Galley",
    "age": 41
    }
] 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With