开发者

Reading JavaScript object properties

开发者 https://www.devze.com 2023-01-30 02:32 出处:网络
I have the following code in JavaScript var result = { \'org.apache.struts\' : \'4567ty5y7u8j89hjk789\',

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) // ret开发者_开发知识库urns 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?


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);


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


The problem is that your variable has dots in it. I would guess that javascript mandates interpreting this as nested objects which are not really existing. So, use

result["org.apache.struts"]

to get the value.


You'll have to use ':' between the labels and values of the object and define 'org.apache' as an object too. Like this:

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

If you want to us 'org.apache.struts' as a real label, Andy E's answer is the solution.

0

精彩评论

暂无评论...
验证码 换一张
取 消