-1

I am sorry this seems like an easy answer but I am not really good at programming, I am trying to get a value from an API, I can get the JSON but I only need one value and the other is unnecessary, this is the JSON: https://www.dnd5eapi.co/api/monsters/ =>

"results": [
{
"index": "aboleth",
"name": "Aboleth",
"url": "/api/monsters/aboleth"
},
{
"index": "acolyte",
"name": "Acolyte",
"url": "/api/monsters/acolyte"
},
{
"index": "adult-black-dragon",
"name": "Adult Black Dragon",
"url": "/api/monsters/adult-black-dragon"
}]

and so on,

I am only trying to get the index of each one.

Thank you in advance.

Aqua
  • 37
  • 8

1 Answers1

0

You can convert it to an object pull the data that you need.

const data = JSON.parse(results) // Assuming the variable containing your json is called results

// Make an array of only the indexes
const indexes = data.results.map(v => v.index)

Update: OP Requested

      const uri = "https://www.dnd5eapi.co/api/monsters/";
      // Promises
      fetch(uri)
        .then((res) => res.json())
        .then((data) => {
          const indexes = data.results.map((v) => v.index);
          console.log(indexes);
        });
      // Async Await
      async function getData() {
        const res = await fetch(uri);
        const data = await res.json();
        const indexes = data.results.map((v) => v.index);
        console.log(indexes);
      }
      getData()
Uzair Ashraf
  • 1,171
  • 8
  • 20
  • SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () i think JSON.parse is making the issue, and i changed my variable to results to avoid confusion – Aqua Dec 23 '21 at 19:20
  • Can you log the value to the console before you parse it? can you tell me what the data looks like? – Uzair Ashraf Dec 23 '21 at 19:22
  • "results": [ { "index": "aboleth", "name": "Aboleth", "url": "/api/monsters/aboleth" }, { "index": "acolyte", "name": "Acolyte", "url": "/api/monsters/acolyte" }, { "index": "adult-black-dragon", "name": "Adult Black Dragon", "url": "/api/monsters/adult-black-dragon" }] – Aqua Dec 23 '21 at 19:26
  • This is odd, are you sure it's JSON? Where is the data coming from? Can you tell me the data type? `console.log(typeof results)` – Uzair Ashraf Dec 23 '21 at 19:29
  • this is the api i am getting the information from, https://www.dnd5eapi.co/api/monsters/ but i am only taking .results, i don't think i would be able to use .results if it wasn't json – Aqua Dec 23 '21 at 19:31
  • I'll write it out with a fetch request as well then – Uzair Ashraf Dec 23 '21 at 19:32