如何动态创建 JavaScript 数组(JSON 格式)?

IT技术 javascript json
2021-01-18 04:34:25

我正在尝试创建以下内容:

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.                                  

} // End Employees

我开始了

 var employees = new Array();

如何继续动态创建数组(可能会firstName随变量变化)?我似乎没有得到正确的嵌套数组。

4个回答

我们的对象数组

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

与 for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

或使用Array.prototype.map(),这更干净:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}
var accounting = [];
var employees = {};

for(var i in someData) {

    var item = someData[i];

   accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

employees.accounting = accounting;
这比上面的例子要好,这也告诉了如何动态添加数组。
2021-03-27 04:34:25
但是如果我在另一个文件中传递它,它是未定义的。
2021-04-04 04:34:25
如果我需要该数组的名称是动态的怎么办?
2021-04-06 04:34:25
var student = [];
var obj = {
    'first_name': name,
    'last_name': name,
    'age': age,
}
student.push(obj);

我所做的与@Chase 的回答略有不同:

var employees = {};

// ...and then:
employees.accounting = new Array();

for (var i = 0; i < someArray.length; i++) {
    var temp_item = someArray[i];

    // Maybe, here make something like:
    // temp_item.name = 'some value'

    employees.accounting.push({
        "firstName" : temp_item.firstName,
        "lastName"  : temp_item.lastName,
        "age"       : temp_item.age
    });
}

那工作形成了我!

我希望它对其他人有用!

变量项来自哪里?
2021-04-01 04:34:25
它现在已修复@IrfanRaza
2021-04-06 04:34:25