1

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, I will be getting the list of repeated values from server something like below.

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

I have to create an array of object and fill these values in it.

I am trying to initialize an array like

var myArr = []; 

and I want to add object with properties to it dynamically, something like below.

var myobj = {}

for(int i=0;i<length;i++)
{
myobj[i].name = serverrespOBJ.name;
myobj[i].lastName= 'serverrespOBJ.lastname';
myArr.push(myobj)
}

I am getting the error that name can not be added to undefined, so i believe, my way of adding items to the object is incorrect.

I am trying to find a good example but could not get it. Any help would be appreciated.

Thanks

1
  • You should pick a correct answer! Commented Jul 1, 2014 at 6:36

4 Answers 4

5

You'll be wanting something like this:

var data = { employees: [] }   // initially empty

data.employees.push( {
    firstName: 'John',
    lastName: 'Doe'
} );
Sign up to request clarification or add additional context in comments.

4 Comments

@Gendaful no, please don't do that, it invalidates answers already provided.
@Gendaful in any event, your problem is that you need to create myobj inside the loop, otherwise you're just adding the same object to the array over and over. You also need to lose the [i] dereference - myobj is an object, not an array.
Thanks Alnitak, So in short, I am creating an array myArr and then creating myObj inside for loop such as myObj = {}. After that, I am adding the items such as myobj.name = 'abc, myobj.lastname = def etc. and then adding the obj to the array like myarr.push(myobj), but whenever I am trying to retrieve it with myarray[0].name, it always returns undefined, what do you think I am missing here?
@Gendaful perhaps the source data you're trying to put into myObj is undefined?
1

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 = 10 or myObj['new'] = 10

More advanced :

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

Comments

1

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

4 Comments

This is a valid JSON!
No, it isn't. JSON is a string serialisation format. What you have is a JS object literal.
The one you are talking about is array JSON encoded, user is asking about JSON array!!
No, there's no such thing as a "JSON array". There are "arrays encoded in JSON format". No such entity appears in the question, nor in your answer.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.