chrishenn
chrishenn

Reputation: 29

Return value of each key in object in a for loop

I have an object and an array:

m = { "1": ["2", "3"], "6": ["4", "5"] };
var p = ["1", "6"];

I have a for loop:

for (var i = 0; i < p.length; i++) {
    // Return an array that is the value of a key in m, for each key specified in p
    var array = m[p[i]]; 

    // do stuff with array
}

Any reason why the above does not work? array is still undefined after the for loop runs.

Upvotes: 0

Views: 2307

Answers (3)

Pavel Strakhov
Pavel Strakhov

Reputation: 40512

Your declaration of m = { "1": ["2", "3"], "6", ["4", "5"] }; gives syntax error for me. I assume you mean m = { "1": ["2", "3"], "6": ["4", "5"] };.

p.length is 2, so you have 2 iterations of the loop. In first iteration values of your expressions are:

i = 0
p[i] = "1"
m[p[i]] = m["1"] = ["2", "3"]

In second loop:

i = 1
p[i] = "2"
m[p[i]] = m["2"] (undefined)

You have only m["1"] and m["6"], no m["2"]. That's why array is undefined in the last iteration. So it remains undefined after the loop.

You may correct m declaration as following:

m = { "1": ["2", "3"], "2": ["4", "5"] };

Now you will get array = ["4", "5"] after the loop.

I can advise you not to store integers in strings. Use 2 instead of "2". Otherwise it can cause errors in the future. For example, 2 + 2 = 4 and "2" + "2" = "22". If you have "2" from some other code, use parseInt to convert it to a normal number.

Also, you don't have to create p variable with list of keys. You can simply use for..in loop to iterate through keys of your object:

m = { 1: [2, 3], 2: [4, 5] };
for(i in m) {
  var array = m[i];
  //do stuff
}

Keep in mind that for..in doesn't guarantee to preserve the order of keys. However, all existing implementations of for..in do preserve the order.

Upvotes: 0

Danilo Valente
Danilo Valente

Reputation: 11352

The error happens because you have this declaration:

var p = ["1","2"];

But the m properties are:

m = {
    "1": [2,3],
    "6": [4,5]
}

So in p[1] makes your program read m["2"] but it doesn't have a "2" property. Use this code instead:

var p = ["1","6"];

Upvotes: 1

comfortablejohn
comfortablejohn

Reputation: 645

Also I think p should be [1,6] as well? Since you're using it to reference the keys in the object m.

Upvotes: 2

Related Questions