0

I have a JSON response in the following format.

 {
  "_meta" : {
               "next-person-id" : "1001",
               "totalPersons" : "1000"
            }
 }

I am using Angular's $http service to retrieve this and trying to access next-person-id attribute in javascript like the following,

  $http.get(url).then(
        function(response){
              console.log(response._meta.next-person-id);
        }
  );

But the next-person-id in the response is undefined always. But I'm able to access totalPersons attribute. Is there any problem with getting attributes with '-' character in javascript?

JPS
  • 2,730
  • 5
  • 32
  • 54
  • You can check JavaScript variable name validator from this link https://mothereff.in/js-variables#%E0%B2%A0%5f%E0%B2%A0 – Shaishab Roy Jan 27 '16 at 08:29

3 Answers3

7

Use bracket notation:

console.log(response._meta['next-person-id']);

A possible alternative is to change the keys to use underscores, so that _meta.next_person_id would work.

1

You cant write variables using - as it is also a minus sign.

To solve this, use square bracket notation:

console.log(response._meta['next-person-id']);
Undefined
  • 11,234
  • 5
  • 37
  • 62
-1

Yep true, because in JavaScript you can use Latin letters, numbers and $ _ symbols for variables or properties.

If you want to use -, you should escape it with string quotes.

like this

var obj = {
   'next-person-id': 2
}

console.log(obj['next-person-id']); // 2

Explanation:

In Global scope - means minus. It tries to subtract person from name. So you will get an error like this:

ReferenceError: name is not defined

In JS you can access to object property in 2 ways

1) Dot nation

obj.property

2) Square bracket nation

obj['property']

Here you need to parse string, so as you know in string you can have any symbols except string quote symbol (it will close the string)

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation

Ruben Yeghikyan
  • 497
  • 2
  • 6
  • 19