Hell0 Hell0 - 10 days ago 5
Javascript Question

Iterating over javascript object- part II

hello and thank every one.
Updated link on kopy.io.

var gems = [...,

{
id: 3,
name: 'Level-3',
row: {
r1: '*-*-*',
r2: '**-**',
r3: '*-*-*'
},
canPushtoDb: true,
hideLevel: true,
status: 1
//canvas
}

];


Now i'm trying to iterate over some object like this:

var text;
var arr;
var arr2 = gems[0].row;


for( arr in arr2){
text += '<br />' + arr2[arr] + '<br />';
}


But is not working completly:

enter image description here

//* If i will do a kind of graphic map:
// var something = * * * * * <--- row1
// * * * * * <--- row2
// * * * * * <--- row3
// somthing = [x][y]


So i'm keeping things on
gems[]
array, easy to edit/change/modify.
Thats realy the problem because in other way i'd must to implement a
kind of function on each level.
I need a way to iterate over 'row' member after check on 'id' or 'name'
key value.

I'm confused because i can acces individualy on each member like:
gems[2].name ---> Level-3
or
gems[1].row.r2 ---> -***-
. But it is not
what i want. I searching for a loop that after check on some 'value'
iterate trought 'row' member. for example: if
level == id
then loop on
gems[i].row
. But i can't find the way.



var gems = [{
id: 1,
name: 'Level-1',
row: {
r1: '*****',
r2: '-***-',
r3: '--*--'
},
canPushtoDb: true,
hideLevel: false,
status: 1
//canvas
}, {
id: 2,
name: 'Level-2',
row: {
r1: '**-**',
r2: '-*-*-',
r3: '-***-',
},
canPushtoDb: true,
hideLevel: false,
status: 1
//canvas
}, {
id: 3,
name: 'Level-3',
row: {
r1: '*-*-*',
r2: '**-**',
r3: '*-*-*'
},
canPushtoDb: true,
hideLevel: true,
status: 1
//canvas
}

];


var text;
var arr;
var arr2 = gems[0].row;


for (arr in arr2) {
text += '<br />' + arr2[arr] + '<br />';
}
document.write(text);




Answer

Why not make row property to an array, which is easily iterable, at least better than an object with properties?

row: ['*-*-*', '**-**', '*-*-*'],

If you like to keep the object, you could iterate over the keys

['r1', 'r2', 'r3'].forEach(function (k) {
    console.log(gems[1].row[k]) //do something 
});