Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading JavaScript object properties

I have the following code in JavaScript

var result = {
    'org.apache.struts' : '4567ty5y7u8j89hjk789',
    'firstName' : 'Thorpe',
    'surName' : 'Obazee'
}

When I try to read result:

// this works
sys.puts(result.firstName) // returns Thorpe
sys.puts(result.surName) // returns Obazee

The problem comes when I read the other property

sys.puts(result.org.apache.struts) // return an error

Error: Expected 'TypeError: Cannot read property 'apache' of undefined

How should I read this so that I can access the information I put?

like image 393
Teej Avatar asked Sep 07 '26 23:09

Teej


2 Answers

You can use bracket notation to access properties whose names contain characters invalid for dot notation:

result["org.apache.struts"]

If you want to add further levels to your object so that you can use dot notation, you need to declare another object for each level, e.g.:

var result = {
    org: { apache: { struts: '4567ty5y7u8j89hjk789' } },
    firstName: 'Thorpe',
    surName: 'Obazee'
}

alert(result.org.apache.struts);
like image 110
Andy E Avatar answered Sep 10 '26 12:09

Andy E


The issue is that you're adding it as a whole key instead of another object, access it like result['org.apache.struts'].

Or you can change the way you create result:

var result = {
    org : {
        apache : {
            struts : '4567ty5y7u8j89hjk789'
        }
    }
    'org.apache.struts' = '4567ty5y7u8j89hjk789',
    'firstName' = 'Thorpe',
    'surName' = 'Obazee'
}
like image 35
Josh K Avatar answered Sep 10 '26 11:09

Josh K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!