문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top