Retrieving JSON Data using Fetch

My JSON file consists of a simple object containing 2 arrays:

{ 
"key1": ["a", "b", "c"],
"key2": [ "d", "e", "f"] 
}

When using JavaScript, I fetch the data and push it into an array to use it.

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(data))

console.log(myArray); // This results in a nested array

console.log(myArray[0]); // Undefined 

Looping through myArray also returns //undefined

Using spread syntax or concat leads to //Found non-callable @@iterator

How can I access the content of that array?

Answer №1

According to @Gavin's suggestion, ensure that your console.log statement runs after the completion of the fetch operation. One approach to achieve this is by including it within another then block.

fetch(jsonData)
.then(answer => answer.json())
.then(data => myArray.push(data))
.then(() => console.log(myArray[0]));

Output:

https://i.sstatic.net/lINVm.png

Answer №2

Once the JSON information is obtained, Just execute

const list=Object.values(jsonData)

What I was trying to say is

fetch(location).then((response)=>{
response.json().then((data)=>{
const list=Object.values(data)

Answer №3

Here is what you should do:

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(response => response.json())
.then(data => myArray.push(...data)) //Utilizing the spread operator

UPDATE If the spread operator is not functioning in your project, you can try this approach:

const jsonData = '/things.json';
const myArray = [];

fetch(jsonData)
.then(response => response.json())
.then(data => myArray = data);

If the ... syntax is not working for your projects, there are several solutions available, such as adjusting the target in your tsconfig file to "target": "es5"

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

Please rewrite the following sentence: "I am going to the store to buy some groceries."

As I navigate through my styled HTML page, an interesting sequence of events unfolds. When the Create New List button is clicked, a pink div emerges, contrasting with the orange hue of the All Lists div. At this moment, a new user has joined but hasn' ...

After developing a React application to fetch data from my own API, I encountered the following error message: "TypeError: video.map is not a function". See the code snippet below:

import React, {useEffect, useState} from "react"; import Axios from "axios"; const VideoPage = () => { const [video, setVideo] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchVideoData = async() =&g ...

Tips for passing the element ID as an argument in the jQuery upvote plugin function

var updateVote = function(data) { $.ajax({ url: '/vote/', type: 'post', data: { id: data.id, up: data.upvoted, down: data.downvoted, ...

Three.js dynamic bone animation: bringing your project to life

Can transformations be applied to the bones of a 3D model in three.js to create a dynamic animation? I attempted to move and rotate the bones of a SkinnedMesh, but the mesh did not update. loader = new THREE.JSONLoader(); loader.load(&apos ...

Credit for the Position swipejs

After integrating a swipeJS photo slideshow into my jQuery mobile application, I encountered an issue. I am trying to create points for counting the pictures similar to what is seen on this page: Although I have added the necessary HTML and CSS code to my ...

Looking for the most effective method to parse through multiple json files located in an S3 directory and subsequently import them into a MySQL table?

I am currently managing an S3 folder containing over 40,000 JSON files, each following a format similar to [{"AAA": "XXXX", "BBB": "XXXX", "CCC": "XXXX"}]. My goal is to consolidate these files into a structured table for potential data transformation and ...

VueJS not refreshing DOM after AJAX data modification

Utilizing Vue.js to make changes to my DOM, I have implemented the fetch_data() method. This method attempts to update data.messages to display 'Love the Vue.JS' once the AJAX call is successfully completed. The AJAX call executes successfully a ...

Finding a solution to the type issue of error handling in Route Handler with NextJS

I'm working on a route handler located at app/api/transactions/route.ts. Here's a snippet of the code: import { NextRequest, NextResponse } from "next/server"; import { AxiosError } from "axios"; import axios from "../axi ...

Discovering the destination link of a website while utilizing GM_xmlhttpRequest

Picture yourself browsing a webpage called "www.yourWebsite.com" and utilizing userscripts in Tampermonkey to extract data from another site using the GM_xmlhttpRequest function. As you make requests with the GM_xmlhttpRequest function to visit "exampleWe ...

Graphical Interface for an HTTPAPI

After successfully building a REST API in Node.js using Express that includes queue functionalities, my next goal is to develop a web interface for this API. As a newcomer to JavaScript and Node.js, I would greatly appreciate any advice or guidance on ho ...

Is CoffeeScript used in package.json and bower.json configurations?

I am interested in creating my package.json and bower.json files using CoffeeScript. Even though I am using Gulp, I am still quite inexperienced when it comes to writing Gulp tasks. Is there a way for NPM and Bower to read CoffeeScript configuration file ...

Ensure that the Ajax calendar extender does not allow the selection of past dates

I'm currently using an ajax calendar extender along with JavaScript to prevent users from selecting past dates. However, I'm encountering a problem: When the user selects a past date, it works correctly If the user chooses a future date, it als ...

Add the href attribute for linking to Google Maps

When working on my app, I utilize the geocoder in conjunction with json to display markers on a map. The code snippet looks like this: ... $.get("get_organizations.json", function( data ) { $.each( data, function( index, organiza ...

Tips for resolving the 'route.search' bug in Express.js

I recently started working on a basic Express app (with Node) and I am in the initial setup phase. However, I have encountered an error that is proving to be quite challenging to resolve. Despite my attempts to search for solutions online and browse throu ...

Determining If a setInterval Function is the Sole Factor Preventing an App from Exiting

Is there a method to determine the number of tasks remaining for Node before it automatically exits because all tasks are completed? I am interested in utilizing setInterval but only while the application is still running other processes. I do not want t ...

The $ref feature in JSON schema does not support relative paths

There are 3 different schemas in my collection: The first one is the child schema: { "title": "child_schema", "type": "object", "properties": { "wyx":{ "type": "number" } }, "additionalProperties": false, ...

What is the recommended way to select a checkbox using JQuery?

I have exhausted all options and nothing seems to be working. This is the checkbox in question: <input type="checkbox" onchange="WriteFormSelections('SearchForm', 'AccommodationType', 'AccommodationTypeSelections', 'A ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Angular Bootstrap-Select: Displaying options even after selection

There seems to be a bug in the angular bootstrap select demo section. After selecting an option, the dropdown continues to display options instead of hiding them. This issue does not occur when the ng-model attribute is omitted. You can view an EXAMPLE he ...

Tips for combing 2 JSON Arrays using Groovy

Looking to combine two JSON arrays into one using Groovy scripting. def branchTags = new JsonBuilder() branchTags branches, { String branch -> tag branch type 'b' } println(branchTags.toString()) //produces [{ ...