Accessing Object Key/Value pairs without knowing the name

How do I access a key or value if I don’t know its name (or if it might change by the runtime)?

let object = {first: "John", last: "Smith", age:25, height:5};
console.log(object.last);// Smith, as expected

But what if I don’t know the keys or values ahead of time? Shouldn’t I use Object.keys() to retrieve an array of the keys first, and then accessing it that way?

let keys = Object.keys(object); // retrieving keys and put them into an array
console.log(keys); // now keys contains [ 'first', 'last', 'age', 'height' ] 

So:

console.log(object.first); // John

but

console.log(object.keys[0]); // Cannot read property '0' of undefined

Am I missing something very fundamental?

Thank you!
Sidney

You can use bracket notations, which you can pass in variables. Then once your app is running, you can dynamically retrieve a value from an object.

A common scenario is when a user interacts with a form. You can retrieve name property of an input field when a form is submitted, then access names of inputs to modify form’s values.

Something like…

<input type="text" name="name" id="name" value="John" />

JS...
const name = document.getElementById("name");

YourObj[name] = name.value;
1 Like

Hello Sidneyyin, when you use
object.keys[0]
you are looking for the property keys in the object.

Try this instead:
object[keys[0]]

1 Like