0

How to have object inside of an Array and Iterate to access Objects one by one. Please help to solve this.

var mainVals = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var hubVals  = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];

var posit = {1:mainVals,2:hubVals};

  for (var i = 1;i <= 2;i++)
         {
             var obj = posit.i;       
             alert("obj:"+obj); // which gives undefined
         }  
1
  • 1
    use bracket notation: posit[i] Commented Aug 7, 2014 at 10:14

2 Answers 2

3

You need to use square-bracket notation when the property you're wanting to read is dynamic:

var obj = posit[i];
Sign up to request clarification or add additional context in comments.

Comments

0

The correct code should be something like this, since you have two arrays inside of each other:

var mainVals = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var hubVals  = [{id:1,value:[{},{}]},{id:2,value:[{},{}]}];
var posit = {1:mainVals,2:hubVals};

for (var i = 1;i <= 2;i++)
     { 
        for(var j = 0; j <= 1; ++j){
           var obj = posit[i][j];       
           alert("obj:"+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.