Home > Enterprise >  How can I fetch a specific array from the JSON data and display it?
How can I fetch a specific array from the JSON data and display it?

Time:11-20

Firstly apologies as I am fairly new to fetching from an API and I am trying to learn.

I need to fetch "name" , "age" and "phone" from "id" 1 from "is" and display it when click on button. This is my javascript-fetch-api.js file:

I'm not sure how to fetch only from id 1 "is"

const events = [{
  "id": 1,
  "language": {
    "is": {
      "name": "Ali Sakaroğlu",
      "age": 27,
      "phone": "05368218685",
      "tags": [
        "Gallery",
        "STAK",
        "Gallery Julius",
        "mom",
        "young",
        "lorem",
        "ipsum",
        "show",
        "born",
        "worm",
        "dorm",
        "norm",
        "dlla"
      ]
    },
    "en": {
      "name": "Ali Sakaroğlus",
      "age": 27,
      "phone": "05368218685",
      "tags": [
        "Gallery",
        "STAK",
        "Gallery Julius",
        "mom",
        "young",
        "lorem",
        "ipsum",
        "show",
        "born",
        "worm",
        "dorm",
        "norm",
        "dlla"
      ]
    }
  }
}]


let output = '<ul>';
events.forEach((event) => {
  output  = `<li>${event.id})  Name: ${event.name} - Age: ${event.age} - Phone: ${event.phone} </li> `;
});

output  = '</ul> <hr>';
document.getElementById('output').innerHTML  = output;
<div id="output"></div>

CodePudding user response:

inside event you have id and language, not name, age and phone. if you want to get name, age and phone from "is", you should type:

 event.language.is.age
 event.language.is.name
 event.language.is.phone

CodePudding user response:

You can drill down on the object like this to get name etc from the is property:

      output  = `<li>${event.id})  Name: ${event.is.name} - Age: ${event.is.age} - Phone: ${event.is.phone} </li> `;
  • Related