javascript – 如何在JSON中更好地构造数组数组

前端之家收集整理的这篇文章主要介绍了javascript – 如何在JSON中更好地构造数组数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在以下 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

解决方法

它将需要重组,以便您消除“会计/销售”属性并使员工成为一个对象数组.

示例: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
    },// new property for this object
    "firstName": "Jim",// Fourth Element
    "lastName": "Galley","age": 41
    }
]

猜你在找的JavaScript相关文章