0

I am trying to create an array with the following data as example. I want to set the named index dynamically based on the user selected value. But when I set the index to a variable, the declared variable name is considered a string in the array and set as the array index name.

var country = userInputFromUi;
var cities = [a,b,c,d];

array.push({
country:cities
})

Expected result
userInputFromUi:[a,b,c,d]

actual result
country:[a,b,c,d]

Not sure if I am understanding something wrong here.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
user6591323
  • 69
  • 2
  • 11

1 Answers1

1

Use computed property names like so:

array.push({ [country]: cities });
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79