Declare a JSON array of Objects and add items dynamically

后端 未结 4 616
心在旅途
心在旅途 2021-01-26 04:56

This is stupid but i am missing something and could not reach the conclusion. I am trying to initialize a JSON Array and trying to add JSON Objects to it run time. For an exampl

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-26 05:57

    You can init a new json object like this:

    var jsonObj = {};
    jsonObj.employees = [];
    jsonObj.employees.push({"firstName":"Waqar", "lastName":"Alamgir"});
    

    or add data in existance like this:

    var jsonObj = {
        "employees":[
            {"firstName":"John", "lastName":"Doe"},
            {"firstName":"Anna", "lastName":"Smith"},
            {"firstName":"Peter", "lastName":"Jones"}
        ]
    };
    
    jsonObj.employees.push({"firstName":"Waqar", "lastName":"Alamgir"});
    
    console.log(jsonObj);
    

提交回复
热议问题