Skip to content Skip to sidebar Skip to footer

Declare A Json Array Of Objects And Add Items Dynamically

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 example,

Solution 1:

You'll be wanting something like this:

vardata = { employees: [] }   // initially emptydata.employees.push( {
    firstName: 'John',
    lastName: 'Doe'
} );

Solution 2:

Its simple init first the object or array you want to play dynamicly e.x:

var myArr = [], myObj = {};

Now if adding element to them:

myArr.push(10);
myObj.new = 10or myObj['new'] = 10

More advanced :

myArr.push(myObj); //[10, {'new':10}] --> looks our object

Solution 3:

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);

Solution 4:

Check this fiddle - http://jsfiddle.net/FamBn/1/

HTML:

<input type="text"id="firstname" />
<input type="text"id="lastname" />
<input type="submit"id="add" />
<div id="dsp"></div>

JS:

var employees=[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
];

$('#add').click(function(){
    var fname=$('#firstname').val();
    var lname=$('#lastname').val();
    employees.push({
        firstName: fname,
        lastName: lname
    });
    var output = '';
    for (var i=0; i<employees.length; i++) {
        output += "FirstName: " + employees[i].firstName + " LastName: " + employees[i].lastName;
    }
    $('#dsp').html(output);
    console.log(employees);
});

Post a Comment for "Declare A Json Array Of Objects And Add Items Dynamically"