0

I have a variable that have a dynamic value:

var location = 'state_name'

I want to use it in associative array as a key just like this:

  array.push({
        location: value,
        ...
  });

It should save a key as state_name instead of location. How to do this?

ggDeGreat
  • 1,098
  • 1
  • 17
  • 33

1 Answers1

1

location is a reserved word in JavaScript. Use some other name as variable. Try with square bracket ([]) which allows property names as variables:

var array = [];
var loc = 'state_name';
array.push({
      [loc]: 'test'
});
console.log(array)
Mamun
  • 66,969
  • 9
  • 47
  • 59