Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  85] [ 1]  / answers: 1 / hits: 65039  / 14 Years ago, wed, january 19, 2011, 12:00:00

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

More From » arrays

 Answers
11

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
}
]

[#94156] Monday, January 17, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neilshamarh

Total Points: 181
Total Questions: 94
Total Answers: 104

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
neilshamarh questions
Wed, Jul 8, 20, 00:00, 4 Years ago
Fri, Oct 25, 19, 00:00, 5 Years ago
Mon, Sep 30, 19, 00:00, 5 Years ago
Tue, Apr 30, 19, 00:00, 5 Years ago
Thu, Jan 31, 19, 00:00, 5 Years ago
;