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
}
asked Aug 7, 2014 at 10:11
Jericho
11.1k39 gold badges126 silver badges208 bronze badges
2 Answers 2
You need to use square-bracket notation when the property you're wanting to read is dynamic:
var obj = posit[i];
answered Aug 7, 2014 at 10:14
Jamiec
136k15 gold badges143 silver badges202 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
lang-js
posit[i]