2

I am trying to push object into an array

I have something like these

for(var i=0; i<test.length; i++){
    console.log(test[i])
    console.log(items[test[i]])
    productObj.push( { test[i] : items[test[i]]} );
}

both console.log show stuff but I have an error on the push(). The error is "Uncaught SyntaxError: Unexpected token ["

Can anyone help me about this weird issue? Thanks!

FlyingCat
  • 14,036
  • 36
  • 119
  • 198

3 Answers3

3

Object literal keys need to be constant. test[i] isn't going to work. You'll need to create an empty object and add the key/value pair:

var o = {};
o[ test[i] ] = items[test[i]];

productObj.push( o );
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
2

The keys in an object literal are not evaluated and must be valid identifiers.

You would get the same error just from the object literal: { test[i]: 1 }.

You can use the new keyword in conjunction with an anonymous function to create the object instead:

productObj.push( new function () { this[test[i]] = items[test[i]]; } );

If you find that the above is less readable, then you should create the object in advance:

var temp = {};
temp[test[i]] = items[test[i]];
productObj.push( temp );
Paul
  • 139,544
  • 27
  • 275
  • 264
1

The key of an entry in the {} syntax for creating objects is not looked up as a variable, it must be a valid identifier. test[i] is not a valid identifier due to the brackets, and even if it was it would not get evaluated.

To create a key from test[i], you have to manually add it using the [] syntax.

var v = {};
v[test[i]] = ...
Alexander Gessler
  • 45,603
  • 7
  • 82
  • 122