Home > Software engineering >  Get key and value from object in API call TypeScript
Get key and value from object in API call TypeScript

Time:11-26

I have the following API response and would like to get '"Cursed Body": "100.000%"' out of it in typescript so I can use it to render it on an HTML page. Does anyone know how to get it out of the response?

API Response

{
"tier": "gen8ou",
"pokemon": "Gengar",
"rank": "24",
"usage": "8.56600%",
"raw": "316778",
"abilities": {
    "Cursed Body": "100.000%"
},
"moves": {
    "Shadow Ball": "88.237%",
    "Sludge Wave": "87.815%",
    "Nasty Plot": "37.965%",
    "Focus Blast": "33.418%",
    "Thunderbolt": "30.392%",
    "Trick": "30.257%",
    "Substitute": "15.811%",
    "Dazzling Gleam": "11.645%",
    "Hex": "11.447%",
    "Taunt": "9.282%",
    "Will-O-Wisp": "8.897%",
    "Destiny Bond": "8.033%",
    "Energy Ball": "7.778%",
    "Other": "19.022%"
},}

kind regards

CodePudding user response:

This object "Cursed Body": "100.000%" is the key Cursed Body subject to change?

if it is not, then where you want to render it, you can do

"Cursed Body": response.abilities["Cursed Body"]

CodePudding user response:

Try This:

var apiResult = '{"tier":"gen8ou","pokemon":"Gengar","rank":"24","usage":"8.56600%","raw":"316778","abilities":{"Cursed Body":"100.000%"},"moves":{"Shadow Ball":"88.237%","Sludge Wave":"87.815%","Nasty Plot":"37.965%","Focus Blast":"33.418%","Thunderbolt":"30.392%","Trick":"30.257%","Substitute":"15.811%","Dazzling Gleam":"11.645%","Hex":"11.447%","Taunt":"9.282%","Will-O-Wisp":"8.897%","Destiny Bond":"8.033%","Energy Ball":"7.778%","Other":"19.022%"}}';

const obj = JSON.parse(apiResult);
var jsonStringOfCursedBody = JSON.stringify(obj.abilities);
var valueOfCursedBody = obj.abilities["Cursed Body"];
  • Related