Search code examples
javascriptfetch-api

How do I get into the array I got from json?


I have a JSON file. I'm pulling data from this file with fetch. But I want to get the first element in all the elements of the array I pulled. I tried this but couldn't find it. Can you help me ?

MY JSON DATA :

{
    "cols": [
        "Name Surname",
        "Company",
        "Email",
        "Date",
        "Country",
        "City"
    ],
    "data": [
        [
            "Hyacinth Vincent",
            "Duis Corporation",
            "iaculis.enim@magnaCrasconvallis.ca",
            "28/06/2022",
            "Eritrea",
            "Lyubertsy"
        ],
        [
            "Brenden Martinez",
            "Volutpat Nunc Associates",
            "iaculis@estMauris.org",
            "24/03/2021",
            "British Indian Ocean Territory",
            "Colwood"
        ],
        [
            "Lunea Kinney",
            "Ornare Facilisis Eget Incorporated",
            "rutrum.eu@liberoMorbiaccumsan.ca",
            "20/10/2021",
            "Jordan",
            "Yorkton"
        ],
        [
            "Rhona Mooney",
            "Sed Et PC",
            "placerat@sodalesat.ca",
            "10/11/2020",
            "Azerbaijan",
            "Shrewsbury"
        ]
    ]
}

MY JS CODE :

fetch("api/tesodev.json")
  .then((response) => response.json())
  .then((data) => {
    let cols = data.cols;
    let responseData = data.data;
  for (let index = 0; index < responseData.length; index++) {
    let newResponseData = responseData.map(function (el, i) {
        console.log(el[i]);
      });
      
  }
    console.log(cols[0]);
  });

Exactly what I'm trying to do is to get to the first elements of all the elements of the data array. I want to access the data of "Hyacinth Vincent", "Brenden Martinez", "Lunea Kinney", "Rhona Mooney".


Solution

  • You need to access the current row in your for loop, then access the first element of this row.

    fetch("api/tesodev.json")
      .then((response) => response.json())
      .then((data) => {
        let cols = data.cols;
        let responseData = data.data;
        for (let index = 0; index < responseData.length; index++) {
          const myDataRow = responseData[index];
          const theFirstDataOfMyRow = myDataRow[0];
          console.log(theFirstDataOfMyRow); 
        }
        console.log(cols[0]);
      });