0

I have a JSON object that I fetched from an API.

{
  "response": "success",
  "id": "641",
  "name": "Superboy",
  "powerstats": {
    "intelligence": "75",
    "strength": "95",
    "speed": "83",
    "durability": "90",
    "power": "95",
    "combat": "60"
  },
  "biography": {
    "full-name": "Kon-El / Conner Kent",
    "alter-egos": "No alter egos found.",
   .....

I can't use a - because JS thinks it's an operator.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
BobbyOrr4
  • 352
  • 5
  • 14

1 Answers1

0

Property accessors provide access to an object's properties by using the dot notation or the bracket notation. Mozilla

When accessing an object property in JavaScript you can use both:

Object.response // dot notation

Or

Object['response'] // bracket notation

In the object[property_name] syntax, the property_name is just a string or Symbol. So, it can be any string, including '1foo', '!bar!', or even ' ' (a space). Mozilla

In your case, since you have a special character as the property, you would call your biography properties using the bracket notation.

console.log(Object.biography['full-name']); // Kon-El / Conner Kent
console.log(Object['biography']['alter-ego']); //  No alter egos found.

For more details on how objects work in JavaScript you can read up Mozilla's documentation

Sam
  • 2,856
  • 3
  • 18
  • 29