Guide on retrieving JSON data and inserting it into an array with the fetch function in JavaScript

Being new to javascript, I am uncertain about how to properly add JSON data to an array. I am using the fetch command to retrieve the JSON file. Below is the code snippet for fetching the JSON file:

fetch("event.json")
  .then(response => response.json())
  .then(json => console.log(json));

I am now facing the challenge of adding this fetched data to an array. Any assistance on this matter would be highly appreciated!

Below is the JSON that I am currently retrieving:

{
   "id": "1",
   "name": "Tim",
   "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a1f5c8cce1c6ccc0c8cd8fc2cecc">[email protected]</a>",
   "event":[{"id":1,"name":"HomeShow"}]
}

The JSON file contains information on multiple individuals. My goal is to fetch this file, store it in an array, and then iterate through it to extract specific values.

Answer №1

It seems like your JSON file, event.json (or is it actually events.json?), holds an array of objects structured like this:

[
  {
    "id": "1",
    "name": "Tim",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d0934301d3a303c3431733e3230">[email protected]</a>",
    "event": [{ "id": 1, "name": "HomeShow" }]
  },
  {
    "id": "2",
    "name": "John",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c062324220c2b212d2520622f2321">[email protected]</a>",
    "event": [{ "id": 1, "name": "HomeShow" }]
  }
]

To filter this data, you can apply the following logic within the promise's callback function:

fetch('event.json')
  .then(res => res.json())
  .then(events => events.filter(event => event.name !== 'John'))

Note that the above code returns a promise, meaning the filtered data will be available asynchronously in the future.

If you want to use this data later, you should encapsulate it in a function, return the promise, and utilize .then on the returned value to access the filtered content:

function getFilteredEvents() {
  return fetch('event.json')
    .then(res => res.json())
    .then(events => events.filter(event => event.name !== 'John'))
}

getFilteredEvents().then(filteredEvents => console.log(filteredEvents))

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

What is the best way to generate an AWS signature using Javascript?

I've been attempting to generate the AWS Mechanical Turk signature using Node.js, but I'm encountering difficulties. Currently, I am using the code snippet below, but it keeps throwing errors: CryptoJS.HmacSHA1(service + operation + timestamp, p ...

Resetting the CSS for an input field: a step-by-step guide

My situation involves having a global CSS style set for text type inputs, such as: input[type=text] { padding:10px; width:100px; //and many more } Now, I am incorporating a plugin called colorpicker into a specific div. This plugin generates some input e ...

Developing a MySQL DB-driven Node.js dashboard without the need for a poller

After exploring various StackOverflow posts on the topic, I haven't been able to find a solution that fits my specific situation. We have multiple monitoring instances across our network, each monitoring different environments (such as Nagios, Icinga ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...

An issue arises with the Datatables destroy function

Utilizing datatables.js to generate a report table on my page with filters. However, when applying any of the filters, the data returned has varying column counts which prompts me to destroy and recreate the table. Unfortunately, an error message pops up ...

What is the best way to transfer an ID from the external JSON object to the internal JSON

Currently, I am in the process of developing a telegram bot for my fantasy football league; however, I've encountered a minor issue. The problem lies in pulling a JSON file that I intend to upload to my MongoDB database. Specifically, the JSON file ha ...

Aligning a child div within a parent div by using absolute positioning for both

When creating my components dynamically using JS, I utilize position: absolute for both the parent and children elements to achieve the desired placement. But I've encountered an issue with centering a div within another div. Most solutions suggest m ...

Calculating Standard Deviation with JQ Syntax

My task involves calculating the Sample Standard Deviation using jq with an array of numbers. The formula for Sample Standard Deviation can be seen here. I have attempted to break down the code into individual parts such as length and mean, but have stru ...

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js t ...

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

Can JavaScript be used to upload a file directly to memory for processing before transferring it to the server?

I'm exploring the idea of using a JavaScript encryption library (not Java) to encrypt a file before sending it to the server. Is it feasible to perform this process on the client-side and then upload the encrypted file using JavaScript, storing it in ...

Generate Material UI sidebar components that are positioned above all other components

I am currently working on a sidebar component using the Material UI Drawer component. I am looking to add components that align side by side with the sidebar, similar to the green box shown in the image below. https://i.sstatic.net/aAtn6.png After attem ...

Gridlines Collapse upon Rendering in the Griddle Subgrids

Griddle has the capability to support subgrids. In one of the fields, I have a customized component for row selection that triggers a state change. This state change leads to a re-rendering of the component, causing the collapse of the subgrid. However, I ...

The Express API is failing to recognize the data keys that were sent from the React frontend, despite being clearly specified

I am facing an issue while trying to send data to a REST API using React hosted in a separate application. The API does not seem to receive the keys sent, even though I checked the results in Chrome and found this output:(2) ["imageSrc", File]0: "imageSrc" ...

What is the best method for transferring states between components?

When it comes to React JS, I am a beginner looking to develop a ToDo list application. In my project, I have the main page App.js, where I created the component MainBlock. This MainBlock component structures the layout into left and right sides. On the rig ...

Transfer external variables into the image's onload function

I am trying to retrieve image dimensions and then execute additional actions. Since the image onload function is asynchronous, I have decided to handle everything within the onload call. This is my current approach: function getMeta(url, callback) { v ...

Angular 2: Dynamically Adjusting View Components Based on URL Path

Apologies for the unconventional title. I struggled to come up with a better one. My goal is to develop an application with a simple 3-part structure (header / content / footer). The header should change based on the active route, where each header is a s ...

Reading XML and JSON properties using Java's API

Are there any Java open-source libraries available for reading properties from either an XML or JSON file using a single API call, regardless of the format? In Java, the Properties class provides a loadFromXML() method but lacks support for JSON. An idea ...

Adjust the width of the table to scroll horizontally and size down to fit within the

My webpage is structured with a sidebar and content section, using flex display with the sidebar set to 0.15 flex and the content set to 0.85 flex. I want this page to be full width of the viewport. The issue arises when I try to incorporate a table into ...

In the Swiper function of JavaScript within a Django template, the occurrence of duplicate elements (products) is being generated

Experimenting with displaying products in a Django template, I decided to utilize the Swiper js class. This allowed me to showcase the products within a div, complete with navigation buttons for scrolling horizontally. However, when testing this setup wit ...