在for循环中将对象添加到'Json Array of Objects'

时间:2014-09-18 19:06:21

标签: javascript arrays json

这是包含会计和销售数组的对象数组employees。是否可以在一次推送中向会计和销售数组添加新条目?

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

1 个答案:

答案 0 :(得分:1)

以下是解决此问题的一种方法:http://jsfiddle.net/bmartinelle/hrgxc3r7/

for(i=0;i< arrayfirstName.length; i++)
{
       var newEntry = {"firstName" : arrayfirstName[i], "lastName" : arraylastName[i], "age" :         arrayage[i] };

       employees.accounting.push(newEntry);
}

您必须创建一个JSON条目以推送到您的JSON结构 - 然后您可以将该JSON对象添加到您的记帐数组中。