在以下
JSON对象中:
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
如何重组对象,以便我可以访问每个员工名字,如下所示:
employees[0].firstName employees[1].firstName // etc
解决方法
它将需要重组,以便您消除“会计/销售”属性并使员工成为一个对象数组.
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 },// new property for this object "firstName": "Jim",// Fourth Element "lastName": "Galley","age": 41 } ]