0

I have an array that I am adding objects to. I would like to control the number of objects that are added to the array using a number.

for (var i = 0; i < numberOfCountries; i++) {
    chartArray[i] = obj[i];
}

I am trying to get this:

    chartArray[0] = obj0;
    chartArray[1] = obj1;
    chartArray[2] = obj2;
    chartArray[3] = obj3;
    chartArray[4] = obj4;
    chartArray[5] = obj5;
3
  • how are obj1-5 assigned? Commented Dec 2, 2013 at 13:56
  • 2
    chartArray[i] = window.["obj " + i]; ? Commented Dec 2, 2013 at 13:58
  • 1
    if (chartArray.length > 5) break; Commented Dec 2, 2013 at 13:59

5 Answers 5

1

Assuming the obj variables are available at window scope:

for (var i=0; i<numberOfCountries; i++) {
    chartArray[i] = window["obj"+i];
}
Sign up to request clarification or add additional context in comments.

1 Comment

yes, obj is available at window scope, thanks, this is just was I was looking for.
1

May be you want this?

for (var i=0; i<numberOfCountries; i++) {
    chartArray.push(this["obj"+i]);
}

Comments

0

Assume that the index of for loop is 0:

You have this code:

chartArray[0] = obj[0];

in this code you try to push an elemento of an array named "obj" with index 0 to your chartArray in index 0.

to do what you want you must resolve the name of the object by adding a sequential number to the word "obj" to do so you can use eval().

Try:

for (var i = 0; i < numberOfCountries; i++) {
   //for debug uncomment nexr line 
   //console.log("name:","obj"+i,"eval:",eval("obj"+i));
   if(typeof eval("obj"+i) !== "undefined") return chartArray.push(eval("obj"+i));
}

if object named "obj"+i isn't defined the loop continue to next "Countrie" whitout add to your array.

bye.

Comments

0

I really get the feeling you are asking the wrong question (see https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). The objects you refer to should be in an array in the first place

Comments

-1

you can do this:

var char = new Array();
for (var i = 0; i < number; i++)
{
    char.push(obj[i]);
}

2 Comments

obj is not an array, as per the code under I am trying to get this..
Well I'm sorry, when i saw chartArray[i] = obj[i]; i though obj[i] was working and that he had an error somewhere else while assigning his values.

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.