0

I have this snippet of code:

var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
  arrLiteData.push({ii:{"field1":100,"field2":ii}});
}

...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:

[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...

What am I doing wrong?

Many thanks.

TheBounder
  • 39
  • 4

1 Answers1

0

Quotes are optional for javascript object keys, so {ii:{"field1":100,"field2":ii}} is the same as {"ii":{"field1":100,"field2":ii}} or even {ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.

To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:

{[ii]:{"field1":100,"field2":ii}}

Or build the object in two steps:

var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
  var obj = {};
  obj[ii] = {"field1":100,"field2":ii};
  arrLiteData.push(obj);
}
Axnyff
  • 9,213
  • 4
  • 33
  • 37