1

Let's say I have an object:

var elObject = {
   one: {
    name: "Oliver"}
}

I can access name by doing elObject.one.name and everything is great, but let's say I have this instead:

var elObject = {
       1: {
        name: "Oliver"}
    }

Suddenly, I can't access name through elObject.1.name anymore since I'm using 1 instead of 'one'. Is there a a special escape or something I'm supposed to use with object literal and digits?

0

1 Answer 1

0

You can declare the plain object with number 1 using it as string. Once is not allowed to have a property name starting with number, you can access it using bracket notation.

Example and findle below.

var x = {
    '1' : {
        name: 'Joao'
    }
};
alert(x);
try {
    alert(x['1'].name);
}
catch(e){
    alert(e.message);
}

https://jsfiddle.net/b4c34wLv/

Sign up to request clarification or add additional context in comments.

4 Comments

Hi. Thanks. I changed the answer.
Please don't answer duplicate questions.
It was marked as duplicated after my answer.
It was marked as duplicate about 6 minutes before you posted your answer - timestamps don't lie :-) Maybe you've been subject to one of the grace period bugs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.