views:

42

answers:

3

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)?

+1  A: 

Just do:

var foo = [];
for (/*loop*/) {
    foo.push(['this is a new array', 'with dynamic stuff']);
}
Skilldrick
+1  A: 

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]);
}
Squeegy
+1  A: 

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.

Robusto
谢谢,Robusto. I appreciate the extra way to do it.
rg88