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

I have an ajax request that returns some JSON formatted data. I'm building out a Google Maps display with it so I need to take that data and pass it to a few variables. So I want to build an array like:

var foo = [
    ['A Town', 32.844932, -50.886401, 1, setting1, '<div class="office"><div class="name">Smith</div><div class="location">111 Main Street<br /> Breen, MS<br /> 12345</div><div class="size">18 units<br />300 Foo</div><div class="thelink"><a href="#">Visit</a><br /><a href="#">Output</a></div></div>'],
    ['B Town', 33.844932, -51.886401, 2, setting1, '<div class="office"><div class="name">Jones</div><div class="location">112 Main Street<br /> Breen, MS<br /> 12345</div><div class="size">18 units<br />300 Foo</div><div class="thelink"><a href="#">Visit</a><br /><a href="#">Output</a></div></div>'],
[etc], 
[etc]
    ];

That I can then use to render my google maps locations. I have the JSON data so how do I loop through it and build out such an array? Or is there a better way to do it that I am missing (which is what I suspect, lol)?

share|improve this question

3 Answers

up vote 3 down vote accepted

Just do:

var foo = [];
for (/*loop*/) {
    foo.push(['this is a new array', 'with dynamic stuff']);
}
share|improve this answer

You can use the push function on Array objects to build them dynamically.

var a = [];
var b = [1,2,3,4,5,6,7,8,9];

for (var i=0; i<b.length; i++) {
  a.push(b[i]);
}
share|improve this answer

In addition to Array.push(), you can also assign values directly to Array indices. For example,

var foo = [];

foo[0] = "Foo 0";
foo[19] = "Bob";

This will give you a sparse array with a length of 20 and values in elements 0 and 19.

share|improve this answer
谢谢,Robusto. I appreciate the extra way to do it. – Lothar Oct 1 '10 at 16:30

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.