Dr.PB
Dr.PB

Reputation: 1067

Access obj in for loop

objVar = "one";
varID = ["Result1", "Result2"];
var one = {
  Result1: 5,
  Result2: 100
}

for (i = 0; i < varID.length; i++) {
  textID = '#' + varID[i];
  document.querySelector(textID).innerHTML = "??";
}
<div id="Result1"></div>
<div id="Result2"></div>

In place ofthe question marks (??), I need to get the value of objVar[i]. Is this possible directly (i.e., without a = eval(objVar); a[varID[i]])?

Upvotes: 1

Views: 77

Answers (4)

Pouria Parhami
Pouria Parhami

Reputation: 182

I use console.log for testing, you can use document.querySelector.

var objVar = {

    one: {
        Result1: 5,
        Result2: 100
    },

    two: {
        Result3: 12,
        Result4: 13
    }

};

var varID = ["Result1", "Result2"];
var textID;

//chose object from user or any way you want ...
var customObject = "one";


for (let i = 0; i < varID.length; i++) {
    textID = '#' + varID[i];
    console.log(objVar[customObject][varID[i]]);
}

Upvotes: 0

Jai
Jai

Reputation: 74738

You can call this :

... = one[varID[i]];

actually, objVar can change. depending upon that, object needs to access.

Based on this comment:

... = window[objVar][varID[i]]

objVar = "one";
varID = ["Result1", "Result2"];
var one = {
  Result1: 5,
  Result2: 100
}

for (i = 0; i < varID.length; i++) {
  textID = '#' + varID[i];
  document.querySelector(textID).innerHTML = window[objVar][varID[i]];
}
<div id="Result1"></div>
<div id="Result2"></div>

And other examples can be using Object.keys():

objVar = "one";

var one = {
  Result1: 5,
  Result2: 100
}

Object.keys(window[objVar]).forEach(
     res => document.querySelector('#'+res).innerHTML = one[res]
)
<div id="Result1"></div>
<div id="Result2"></div>

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138257

 window[objVar][ varID[i] ]

And you should probably choose another datastructure:

var lookup = {
 one: {
  Result1: 5,
  Result2: 100
 }
};

...cause you should try not to use window for anything.

Upvotes: 1

Rohit Agrawal
Rohit Agrawal

Reputation: 1521

[EDIT] : As you said that objVar can also change so you can make one object as a property of a parent object and access it. If not then you can make it global and use it as a property of window object though I don't recommend creating global variable.

You can access the property on object one by bracket notation like this:

var masterObj = {
 one : {
  Result1: 5,
  Result2: 100
 },
 two: : {
  Result1: 5,
  Result2: 100
 },
}


document.querySelector(textID).innerHTML = masterObj[objVar][varID[i]];

OR

document.querySelector(textID).innerHTML = window[objVar][varID[i]];//for global variable

Upvotes: 1

Related Questions