Reputation: 397
const data = { bmw: { price: 200 } }
let carName = Object.keys(data).toString()
console.log(carName)
// Output: bmw
let price = data.carName.price
console.log(price)
// Output: TypeError: Cannot read property 'price' of undefined
let price2 = data.bmw.price
console.log(price2)
// Output: 200
why I Can not use the name of the variable to access the price why i do have to type it by myself
thanks
Upvotes: 0
Views: 615
Reputation: 889
You have to use:
let price = data[carName].price
console.log(price)
This is because the carName property does not exist on data object, but the key with the value of the carName variable exists on the data object, so you need to use square brackets to get the price of the car
Upvotes: 1