0

Sorry for the ugly code and if this is an obvious question. I'm having a hard time Googling it.

I have an array like this:

var productDropArea = ['productDropArea5', 'productDropArea6','productDropArea7','productDropArea8','productDropArea9','productDropArea10'];

I also have this object with data in them :

 res.assetData.productMedia5
 res.assetData.productMedia6
 res.assetData.productMedia7
 res.assetData.productMedia8
 res.assetData.productMedia9
 res.assetData.productMedia10

Is there any way I can access this data through a loop dynamicly ?

I have tried something like this:

for (var i = 5, len = productDropArea.length +5 ; i < len; i++) {
    console.log(res.assetData.productMedia+i);
}

Which does not work. Is there any way I could access all the res.assetData.productMedia+i data in my loop?

Bolli
  • 4,974
  • 6
  • 31
  • 47
  • Possible duplicate of [JavaScript property access: dot notation vs. brackets?](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets), [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – ASDFGerte Apr 26 '18 at 00:40
  • Prefer an array instead, that is a smelly object :} – user2864740 Apr 26 '18 at 00:51

2 Answers2

1
console.log(res.assetData['productMedia'+i]);
Evert
  • 93,428
  • 18
  • 118
  • 189
1

You have to use bracket notation to access a property with a variable name (or with any name that can't be expressed with dot notation, such as a string with a - in it).

const obj = {
  productDropArea5: 5,
  productDropArea6: 6,
  productDropArea7: 7,
  productDropArea8: 8,
  productDropArea9: 9,
  productDropArea10: 10,
};
const props = ['productDropArea5', 'productDropArea6', 'productDropArea7', 'productDropArea8', 'productDropArea9', 'productDropArea10'];
props.forEach(prop => console.log(obj[prop]));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320