Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Checking if an object has a property and accessing it

I’m new to TypeScript (and js) and this is probably basic:

const myObj = {
    "name": "Johnny",
    "age": 29
}


const accessProperty = (key : string) => {
    if(key in Object.keys(myObj)) {
        // TODO: access myObj.key...
    }
}
  1. How do I access the property of myObj that is represented by key
  2. Is this the right way to check if key is indeed a property of myObj?

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  1. How do I access the property of myObj that is represented by key

You can access the property via myObj[key]

  1. Is this the right way to check if key is indeed a property of myObj?

Someone posted a link to the optional chaining operator. This is probably the best way to go. There are times when you want to iterate through the keys of an object (mostly when you’re trying to figure out what it is) but in general it is hard to create meaningful code for keys that you’re not expecting, so again using the optional chaining operator is probably the best way to go.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading