Probably this will be a real stupid question to ask but im new in javascript and stuck with dynamic creation of array like in below format:
items = [{
"Date": "2012-01-21T23:45:10.280Z",
"Value": 7
}, {
"Date": "2012-01-26T23:45:10.280Z",
"Value": 10
}, {
"Date": "2012-05-30T23:45:10.280Z",
"Value": 16
}];
Please guide me how do i create above array dynamically using javascript syntax.
Thanks in advance!
Danilo Valente
11.4k8 gold badges55 silver badges71 bronze badges
asked Feb 4, 2014 at 13:36
Milan Mendpara
3,1315 gold badges43 silver badges61 bronze badges
-
2Please share what have you tried so far.Vivek Jain– Vivek Jain2014年02月04日 13:37:30 +00:00Commented Feb 4, 2014 at 13:37
-
Dynamically from what? Current answers are as static as your array literal.Bergi– Bergi2014年02月04日 13:39:52 +00:00Commented Feb 4, 2014 at 13:39
-
var items = []; for(i in d.date) { var arr = i.split("-"); var Item = new function(){ this.Date = arr[0]; this.Value = arr[1]; } items.push(Item);}Milan Mendpara– Milan Mendpara2014年02月04日 13:41:01 +00:00Commented Feb 4, 2014 at 13:41
2 Answers 2
var items = []; // initialize array
items.push({ // add 1st item
"Date": "2012-01-21T23:45:10.280Z",
"Value": 7
});
items.push({ // add 2nd item
"Date": "2012-01-26T23:45:10.280Z",
"Value": 10
});
items.push({ // add 3rd item
"Date": "2012-05-30T23:45:10.280Z",
"Value": 16
});
And to view it:
console.log(JSON.stringify(items));
See:
- Javascript Array
Array.prototype.pushto add elememts
answered Feb 4, 2014 at 13:38
Brad Christie
102k16 gold badges160 silver badges200 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Cerbrus
Why do you use
JSON.stringify for the log?Brad Christie
@Cerbrus: Just a quick and dirty way to visualize the data's there. You could
console.log(items) but then you're having to use the debugger to expand out the object and each element in the array to confirm it's been populated.Do you mean like this:
items = [];
items.push({
"Date": "2012-01-21T23:45:10.280Z",
"Value": 7
});
items.push({
"Date": "2012-01-26T23:45:10.280Z",
"Value": 10
});
items.push({
"Date": "2012-05-30T23:45:10.280Z",
"Value": 16
});
answered Feb 4, 2014 at 13:38
Danilo Valente
11.4k8 gold badges55 silver badges71 bronze badges
Comments
lang-js