Unable to retrieve JSON element using Fetch

I'm attempting to retrieve a JSON file and exhibit its components within a div.

Here is the JSON data I have:

[
    {
       "0":{
          "host_id":"129230780",
          "host_names":"STK Homes",
          "host_since":"2017-05-07T12:45:49Z",
          "nb_listings":"2128",
          "langues":"['English']",
          "localisation":"Londres, Royaume-Uni",
          "is_superhost":"False",
          "is_viewer_profile_owner":"False",
          "reviews_count":"1228",
          "url":"https://fr.airbnb.ca/users/show/129230780"
       },
       "1":{
          "host_id":"121683635",
          "host_names":"Evolve",
          "host_since":"2017-03-20T16:26:31Z",
          "nb_listings":"700",
          "langues":"['English', 'Espa\u00f1ol', 'Fran\u00e7ais']",
          "localisation":"\u00c9tats-Unis",
          "is_superhost":"False",
          "is_viewer_profile_owner":"False",
          "reviews_count":"16495",
          "url":"https://fr.airbnb.ca/users/show/121683635"
       }
    }
]

This is my code. The initial section fetches the JSON data. The subsequent part is intended to showcase the two elements in a div (here I am just printing the outcomes):

 fetch(json object)
        .then(function (response) {
          return response.json(); 
      })
        .then(function (data) {
          appendData(data);
      })
        .catch(function (err) {
        console.log(err);
      });

   
      function appendData(data) {
        for (var i = 0; i < data.length; i++) {
          console.log(data[0][i].host_id) // retrieves only the first host_id
          console.log(data[i][i].host_id) // also retrieves only the first host_id
        }
      } 

Is there a way for me to obtain all the host IDs?

Answer №1

If you want to extract all the host ids from your JSON dataset, simply update the appendData function to iterate through each item in the array and then go through every key within each object to retrieve the host_id value.

function appendData(data) {
  for (let i = 0; i < data.length; i++) {
    const obj = data[i];
    for (const key in obj) {
      const host_id = obj[key].host_id;
      console.log(host_id);
      // Instead of displaying the host_id in the console, consider appending it to a div element
    }
  }
}

Answer №2

Exploring multiple methods to iterate through an object nested in an array.

function main() {
  fetch('...')
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      processData(data);  // Approach #1
      processData2(data); // Approach #2
    })
    .catch(function(err) {
      console.log(err);
    });
}

// Property destructuring + for-in loop
function processData(data) {
  const [hostsObj] = data;
  for (let key in hostsObj) {
    const { host_id } = hostsObj[key];
    console.log(host_id);
  }
}

// Inline property destructuring + Object.values + forEach
function processData2([hostsObj]) {
  Object.values(hostsObj).forEach(({ host_id }) => {
    console.log(host_id);
  });
}

// TESTING PURPOSES ONLY: Override / mock the default Fetch API
window.fetch = () => Promise.resolve({
  json: () => Promise.resolve([{
    "0": {
      "host_id": "129230780",
      "host_names": "STK Homes",
      "host_since": "2017-05-07T12:45:49Z",
      "nb_listings": "2128",
      "languages": "['English']",
      "location": "London, United Kingdom",
      "is_superhost": "False",
      "is_viewer_profile_owner": "False",
      "reviews_count": "1228",
      "url": "https://en.airbnb.ca/users/show/129230780"
    },
    "1": {
      "host_id": "121683635",
      "host_names": "Evolve",
      "host_since": "2017-03-20T16:26:31Z",
      "nb_listings": "700",
      "languages": "['English', 'Spanish', 'French']",
      "location": "United States",
      "is_superhost": "False",
      "is_viewer_profile_owner": "False",
      "reviews_count": "16495",
      "url": "https://en.airbnb.ca/users/show/121683635"
    }
  }])
});

main();
.as-console-wrapper { top: 0; max-height: 100% !important; }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

On IOS, Three.js ensures that the RGB values of a texture are set to zero whenever the ALPHA value

Working on a WebGL project utilizing javascript and the three.js framework, I am in the process of crafting a custom shader with GLSL. In this shader, I must load various lookup tables to utilize individual RGBA values for calculations rather than renderin ...

Is there a way to create triangles on all four corners of an image using canvas in JavaScript?

In my code, I am currently working on drawing rectangles on the corners of an image using JavaScript. To achieve this, I first extract the image data from a canvas element. // Get image data let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height) ...

What is the method to activate map dragging in Leaflet only while the spacebar is pressed?

When using Leaflet maps, the default behavior is to drag the view around by only clicking the mouse. However, I am interested in enabling dragging with the mouse only if the spacebar is pressed as well. I would like to reserve mouse dragging without the sp ...

React form input values fail to refresh upon submission

After attempting to upload the form using React, I noticed that the states are not updating properly. They seem to update momentarily before reverting back to their original values. I am unsure of why this is happening. Take a look at this gif demonstrati ...

Is there a way to determine if a directory is empty using Node.js?

Quite a while back, I submitted a question related to PHP. Now I'm facing a similar situation with Node.js where the code below appears to be sluggish when used in a loop - is there a way to achieve this using only vanilla JavaScript in pure Node.js w ...

How to Show Firestore Query Results in a React Native App

I'm struggling to correctly manage the synchronization, asynchronization, and promises related to querying Firestore. Let me simplify my scenario for you. I have different categories of items and I want to display all the categories along with their r ...

Learn how to create a "generated" texture coordinate in three.js similar to how it is done in Blender Cycles

How can I properly display a texture on a cylinder object using THREE.js without distortion? Currently, the texture appears stretched along the edges of the cylinder as shown here: https://i.sstatic.net/O2YFr.png This issue is based on the texture provide ...

Dispensing guarantees with Protractor

q library offers a unique feature that allows resolving and spreading multiple promises into separate arguments: If you have a promise for an array, you can utilize spread instead of then. The spread function distributes the values as arguments in the f ...

Ensuring form accuracy upon submission in AngularJS 1.5: Understanding the $invalid state in relation to $pristine field

When loading data in a form, I want to allow the user to submit data only if the form is valid. Initially, the form is pristine but invalid. If the user edits any one of the three fields, the form is no longer pristine, which is acceptable. However, the ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

Retrieve a document through Django's rest framework after verifying the user's credentials

Currently, I'm immersed in a project employing Django as the backend. My focus lies on utilizing Django Rest Framework to manage an API for downloading files. @detail_route(methods=['GET'], permission_classes=[IsAuthenticated]) def test(sel ...

Is it possible to display partial html templates by accessing the local url and blending them with the main index.html file?

Is there a way to view partial HTML templates locally without copying them into the main index.html file? I'm looking for a solution that allows me to access my partial templates through a local URL without having to manually paste them into the main ...

Why are the $refs always empty or undefined within Vue components?

I am completely new to working with Vue and I've been attempting to utilize $refs to retrieve some elements within the DOM from a sibling component. My objective is very basic, as I just need to obtain their heights, but I haven't had much succes ...

The JQuery Ajax call returned with a status of 0 and an empty ResponseText

Here is the ajax request I am using: $.ajax({ type: "POST", url: "https://forlineplus.forsa.com.co/projects/validar-redireccion-sio?fup=" + idFup, //contentType: "application/json; charset=utf-8", ...

ng-init assign value to a new object

<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl2" ng-init="person = new Person('Al ...

Incorporate JSON information into HTML dropdown menu using Google API

I'm finding it difficult with this task. Below is a list that needs the name and address inserted into the dropdown menu from the JSON file. <div class="dropdown-list"> <div class="list-container"> <ul class="list" ...

Access to the Express Node.js server is restricted to the machine that is currently hosting the server

I am facing a beginner issue with using express. I am on Ubuntu 14.04 and created a new directory where I ran "express" in the terminal to set up a project template. Following that, I ran "npm install" to install the dependencies. I then made changes to &a ...

Invoking an express route using JavaScript

After successfully defining some routes, including a text input search field at the top of the page, I created a listener function as shown below: $('#tags').keypress(function(e) { if (e.keyCode == 13 && document.getElementById('t ...

Retrieving data from a detailed JSON structure

I have a JSON file like the one below and I am looking to extract the data into an R dataframe. The JSON object contains values for different dates that I want to retrieve and organize in the dataframe. Can you assist me in constructing this? Desired Data ...

How can I dynamically generate properties from a Json string in Winforms using C#?

In our application, there is a method that returns the API object schema as JSON. I am currently exploring ways to extract the property names from this JSON data. For example, after deserialization, I receive the following JSON text: "json": { "C ...