Manuel
Manuel

Reputation: 21

How to loop throught objects with arrays as properties

This is my code: I want to get the first value of the arrays in every property, but it doesnt work. Thanks for help.

var arena = {
 o1: ['gate',1,1],
 o2: ['block',1,1]
};

$(document).ready(function(){
    var canvas = document.getElementById('canvas.arena');
    var xpercent = canvas.width/100;
    var ypercent = canvas.height/100;

    for (var key in arena) {
        if (arena.hasOwnProperty(key)) {
        console.log(key + " -> " + arena[key[0]]);
        }
    }
});

Upvotes: 1

Views: 49

Answers (2)

messerbill
messerbill

Reputation: 5629

you are very close:

var arena = {
 o1: ['gate',1,1],
 o2: ['block',1,1]
};

$(document).ready(function(){
    for (var key in arena) {
      console.log(key + " -> " + arena[key][0]);
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

prepared this fiddle:

https://jsfiddle.net/njvf58ow/1/

Upvotes: 0

yBrodsky
yBrodsky

Reputation: 5041

Almost:

for (var key in arena) {
  console.log(key + " -> " + arena[key][0]);
}

key will always be a property, no need to check.

Upvotes: 2

Related Questions