0

I have a php array that I'm json_encodeing into a JavaScript object. When I preview the object in console, it looks something like this:

Object { 1="some text",  2="something else",  3="extra text"}

Shouldn't I be able to read the value for index 1 like this (pretending my object name is obj)?

obj.1

Doing that gives me the undefined error message. How would I access the value for the exact index of 1?

farjam
  • 2,089
  • 8
  • 40
  • 77

2 Answers2

2

You can only access a property using dot notation if the property name is a valid identifier. Identifiers cannot start with a number.

You have to use square bracket notation for other properties.

obj[1]
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

1- Do not use the word Object

2- Use colon instead of equal

3- Do not forget the semi-colon

4- if your key is number, use braces.

var obj = { 1:"some text",  2:"something else",  3:"extra text"};
console.log(obj[1]);
Mojtaba
  • 4,852
  • 5
  • 21
  • 38
  • 1
    1. They said it was what was display in the console, not their actual code. 2. Ditto. 3. That's best practise, but unnecessary. 4. An explanation as to why would make this a better answer. – Quentin Sep 08 '16 at 21:18
  • @Quentin, tnx. It would be great if you edit it. Or, expand the description of your answer and remove mine. – Mojtaba Sep 08 '16 at 21:20