2

I'm trying to dynamically pass in a value to the type variable in order to get any of the key-values from the testObj object. For example, when type = name, the testResult variable successfully returns 'bob'.

However, if I pass in type as address?.line1, it returns undefined. How can I get it to return the value correctly (in this case '13 test st') using the type variable? A similar principle applies to what I'm working on, so the below is the closest demo I could make.

Thank you.

var testObj = {
    'name': 'bob',
    'address': {
        'line1': '13 test st'
    }
}

// var type = 'name' // works as testResult correctly returns 'bob'
var type = 'address?.line1' // fails as testResult should return '13 test st'

var testResult = testObj?.[`${type}`]
1
  • Because there's no property called address?.line1 on testObj Commented Jul 6, 2021 at 14:29

1 Answer 1

1
  • For accessing a property in an object dynamically, you use object[PROPNAME]. However in your code, you seem to have used testObj.[type], which will not work. You are not supposed to have an access specified in such a case. So you would want to remove that.

  • As for the returning of undefined, as far as I know, you can get only get the property of an object, which could be anything When you put something in the [], it will try to find any property with the name of address?.line1, which obviously does not exist (Remember that you can actually name a property with -, ? and . in an Object, using quotes to define it). That is why it is not working. What you might consider trying, accessing the address property first, then from the returned object, getting the line1 property.
    So you could try,

var { line1 } = testObj["address"]

if you are absolutely sure that, address is a property. Also you could try this

var line1 = testObj["address"]["line1"]

This is the same thing as the previous snippet, just a bit changed. It also has the same requirements to use.

And if you aren't sure about the properties, then you should try to check if the values you're getting exist and then move on.

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.