0

I have a requirement where in I have to populate these variables using for loop in JavaScript digitalData.option1.name1 digitalData.option2.name2 so on..... I tried below code

var i=1;
for(some conditions){
digitalData.this["option"+i].this["option"+i] = value;
i++;
}

But it is showing syntax error and I also tried this Window["digitalData.option+i+.name+i"] But digitaData is not getting populated

1 Answers1

1

Use

var digitalData = digitalData || {}

for (let i = 0; i < 10; i++) {
  digitalData["option"+i] = digitalData["option"+i] || {}
  digitalData["option"+i]["name"+i] = i
}

console.log(digitalData)

You need to do the setting in two steps, otherwise you get a cannot set property name0 of undefined error.

connexo
  • 53,704
  • 14
  • 91
  • 128