0

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
3
  • 2
    Please share what have you tried so far. Commented Feb 4, 2014 at 13:37
  • Dynamically from what? Current answers are as static as your array literal. Commented 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);} Commented Feb 4, 2014 at 13:41

2 Answers 2

3
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:

answered Feb 4, 2014 at 13:38
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you use JSON.stringify for the log?
@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.
1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.