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' ] 


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


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

Am I missing something very fundamental?

Thank you!

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" />

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

YourObj[name] = name.value;
1 Like

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

Try this instead:

1 Like