1

I'm trying to access array which is property of an object, but I can only access letters from property name.

var obj = {};

obj.line0=[0,0];
obj.line1=[0,50];

var pointsLenght = 8;

//things above are just test case sandbox representing small amount of real data

var createPoints = function(obj){
    var i;
    for(var x in obj){
        if (obj.hasOwnProperty(x)) {
            for (i=0;i<pointsLenght;i++){
                if (i%2==0){
                    x[i]=i*50;
                }
                else {
                    x[i]=x[1];
                }
                console.log(i+" element of array "+x+" is equal "+x[i]);
            }
        }
    }
    return obj;
}

And this is what I get in console (Firefox 47.0):

0 element of array line0 is equal l
1 element of array line0 is equal i
2 element of array line0 is equal n
3 element of array line0 is equal e
4 element of array line0 is equal 0
5 element of array line0 is equal undefined
6 element of array line0 is equal undefined
7 element of array line0 is equal undefined

How to access array?

1
  • For clarification what are expected results? Commented Jul 16, 2016 at 17:54

2 Answers 2

2

You are accessing the property name, that is a string. ("line0" and "line1")

For accessing the array belongs to that property name, Just write your code like,

var createPoints = function(obj){
    var i;
    for(var x in obj){
        if (obj.hasOwnProperty(x)) {
            for (i=0;i<pointsLenght;i++){
                if (i%2==0){
                    obj[x][i]=i*50;
                    //obj[x] will give you the array belongs to the property x
                }
                else {
                    obj[x][i]= obj[x][1];
                    //obj[x] will give you the array belongs to the property x 
                }
                console.log(i+" element of array "+x+" is equal "+ obj[x][i]);
            }
        }
    }
    return obj;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution works perfectly, I just chose Ayan answer as a little bit more elegant.
1

Operations need to be done obj[x]. Please Check with the code:

var obj = {};

obj.line0 = [0, 0];
obj.line1 = [0, 50];

var pointsLenght = 8;

//things above are just test case sandbox representing small amount of real data

var createPoints = function(obj) {
  var i, elem;
  for (var x in obj) {
    if (obj.hasOwnProperty(x)) {
      elem = obj[x];
      for (i = 0; i < pointsLenght; i++) {
        elem[i] = (i % 2 == 0) ? (i * 50) : elem[1];
        console.log(i + " element of array " + elem + " is equal " + elem[i]);
      }
    }
  }
  return obj;
}
createPoints(obj);

Comments

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.