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
This question is related to
javascript
arrays
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.
In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently
data = [...data, {"label": 2, "value": 13}]
Examples
var data = [_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
];_x000D_
_x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
For your case (i know it was in 2011), we can do it with map() & forEach() like below
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
Source: Stackoverflow.com