tags:

views:

44

answers:

2

I have a collection that looks like:

var stuff = new Array();

    stuff["col1"] = new Array(
            "key", "value",
            "key2", value2"

    );

And other one that looks like:

var fun = { 

     "key": "value",
     "key2": "value2"
}

I need to loop through each one, and output something like:

INSERT Table1 (c1, c2) VALUES (key, value)

Where the values 'key' and 'value' are coming from the javascript arrays.

(btw, are they both arrays or?)

+2  A: 

First off, you can't actually do array["string"]. Arrays can only have numbered indexes. Objects can have string indexes. So your code should look like this:

var stuff = new Array();

stuff[0] = new Array(
        "key", "value",
        "key2", value2"

);

To loop thorugh each element in the array (or object), you can use for each:

for each(var row in stuff){
  document.write("INSERT INTO Tatble1 (c1, c2) VALUES ("+row[0]+", "+row[1]+")");
}

No, they are not both arrays. The first on is an array, the other one is an object. For example:

fun["key"];//=="value";
Marius
+1  A: 

Actually stuff["col1"] creates an object and stores an array with col1 as the key. The code is fine.

This loops through both the array and the object:

<script>
var stuff = new Array();

stuff["col1"] = new Array(
    "key", "value",
    "key2", "value2"
);

var fun = {"key": "value", "key2": "value2"};

var fun2 = {}
for (var i in stuff["col1"]) {
    if (i % 2 == 0) {
        key = stuff["col1"][i];
        value = stuff["col1"][i+1]
        fun2[key] = value;
    };
}

for (var k in fun) {
    document.write("INSERT Table1 (c1, c2) VALUES ('" + k + "', '" + fun[k] + "')     <br/>");
}

for (var k in fun2) {
    document.write("INSERT Table1 (c1, c2) VALUES ('" + k + "', '" + fun2[k] + "') <br/>");
}


</script>
jbochi