-3

I am just wondering how can i get the property names from a js object. for example, in this case, how can i get "Athlete", "muscle-soreness" and "sleep-quality" ?

{
    "athlete": [
        "Jamie Anderson"
    ],
    "muscle-soreness": [
        "5"
    ],
    "sleep-quality": [
        "5"
    ]
}
JAAulde
  • 19,250
  • 5
  • 52
  • 63
Gary Fan
  • 73
  • 1
  • 8
  • objName.athlete ? – Suresh Atta Aug 08 '17 at 12:37
  • First things first, what is [JSON object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON), after reading that, see [how to access properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors) of an object. – Teemu Aug 08 '17 at 12:37

3 Answers3

2

You can use the Object.keys() function:

var obj = {
    "athlete": [
        "Jamie Anderson",
    ],
    "muscle-soreness": [
        "5",
    ],
    "sleep-quality": [
        "5",
    ]
}

console.log(Object.keys(obj));
Dan Def
  • 1,836
  • 2
  • 21
  • 39
-1

Import it

var data = require('your_file_name.json')

Access it

data["athlete"]
atiq1589
  • 2,227
  • 1
  • 16
  • 24
  • The question is asking how to find the names of the properties the object has. It isn't asking how to get the value if you already know what the property name is. – Quentin Aug 08 '17 at 12:42
  • sorry i understood it wrongly. by "How to access an Object property's name" i thought he is facing problem to import json from file and access it. – atiq1589 Aug 09 '17 at 04:27
-1

You can access it like a normal object by obj.propertyname or by array access, obj['fieldname'].

See snippet below to illustrate multiple ways to parse the data.

var obj = JSON.parse('{\
"athlete": [\
    "Jamie Anderson"\
],\
"muscle-soreness": [\
    "5"\
],\
"sleep-quality": [\
    "5"\
]\
}');
console.log(obj['athlete']);

console.log(obj.athlete);

console.log(obj['muscle-soreness']);

for(key in obj) {
   if(obj.hasOwnProperty(key)) {
      var values = obj[key];
      if(Array.isArray(values)) {
          console.log(key, obj[key].join(','));
      }
      else {
          console.log(key, obj[key]);
      }
   }
}
Tschallacka
  • 27,901
  • 14
  • 88
  • 133