0
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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.