Mathlight
Mathlight

Reputation: 6653

JS loop through objects

First I am sorry because this possibly will be very simple. But I work a lot in PHP, but that syntax won't work in JS.

I've got the following pieces of code:

var rangeArr = [];

// This piece is inside an loop of adding elements...
rangeArr[row_id] = {"row_x": row_x, "row_y": row_y, "row_name": row_name, "row_dir": row_dir, "row_length": row_length, "row_height": row_height};
        row_id++;

I'll get this object for instance (got from Chrome console):

rangeArr
[undefined × 1, 
Object
    row_dir: "lr"
    row_height: "6"
    row_length: "5"
    row_name: ""
    row_x: 45
    row_y: 71
    __proto__: Object
    , 
Object
    row_dir: "lr"
    row_height: "6"
    row_length: "6"
    row_name: ""
    row_x: 95
    row_y: 208
    __proto__: Object
]

I'm using the following piece of code to loop through the object array:

for (var item in rangeArr) {
    if(typeof(item) !== 'undefined'){
        console.log(item.row_x);
    }
}

But I only get undefined errors... When I look into the console log, the whole item contains only the row_id. That means that only the index is retrieved, not the object itself.

As I said before, I have got little to no knowledge about JS Objects, but I thought that this was the right way to do this.

So how can I get my piece of code working so that I can receive the data when needed?

Upvotes: 1

Views: 95

Answers (1)

MrCode
MrCode

Reputation: 64526

In your for in loop, item is actually the array key, not the array element value. To get the object, use rangeArr[item].

for (var item in rangeArr) {
    var obj = rangeArr[item];
    if(typeof(obj) !== 'undefined'){
        console.log(obj.row_x);
    }
}

That said, for in loops are a bad idea on arrays. A basic incremental for loop, or a forEach is preferred. Refer to this question for more info.


It looks like you're generating the incremental keys manually. Instead of that, you might prefer to use Array.prototype.push():

rangeArr.push({"row_x": row_x, "row_y": row_y, "row_name": row_name, "row_dir": row_dir, "row_length": row_length, "row_height": row_height});

Upvotes: 2

Related Questions