1

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?

1 Answer 1

2

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});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that indeed worked. I use the row_id somewhere else to, so the push is not an option. But thank you for your sugestion, didn't knew that was also possible in JS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.