Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

this is an array of objects,

    var data = [{"label" : "1",  "value" : 12},
{"label" : "1", "value" : 12 },
{"label" : "1", "value" : 12},
{"label" : "1", "value" : 12}];

how can i add values to these dynamically? i tried the below code but no success

var lab=["1","2","3", "4"];
var val= [42,55,51,22];
var data =new Array();
    for(var i=0; i<4; i++)  {
       data[i].label= lab[i];
       data[i].value=val[i];    }

anyone please.. thanks in advance

share|improve this question
1  
You know that there are 3x lab and 4x val? – xanatos Oct 22 '11 at 9:25
yes i know, its only here mistakenly.. thanks for informing me – ABC Oct 22 '11 at 9:37

1 Answer

up vote 2 down vote accepted

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.