-3

i am trying to do the following:

var cars = [];
var newCar = "toyota";
cars.push({
newCar: {
year: 2000,
}
})

it saves newCar as "newCar", not as "toyota". How can I do it?

Unaidu
  • 73
  • 1
  • 7
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+object+key+from+variable) of [JavaScript set object key by variable](https://stackoverflow.com/q/11508463/4642212). – Sebastian Simon Jan 17 '21 at 21:25

2 Answers2

1

You want to use a dynamic property key.

var cars = [];
var newCar = "toyota";
cars.push({
 [newCar]: {
 year: 2000,
}
})
Uzair Ashraf
  • 1,171
  • 8
  • 20
1

Use computed property name

var cars = [];
var newCar = "toyota";
cars.push({
[newCar]: {
year: 2000,
}
})

console.log(cars)
ptothep
  • 415
  • 3
  • 10