How can we retrieve an API response using Fetch, manipulate it with JSON.stringify(), and what are the next steps in

After countless attempts, I still can't figure out what's missing here.

I'm utilizing fetch to retrieve data from Mapbox:

var response = fetch(myURL)
.then(response => response.json())
.then(data => console.log(JSON.stringify(data)))

Despite successfully logging the fetched data in the console, I'm struggling to manipulate it into a usable format. Specifically, I just need the latitude and longitude coordinates, but all my efforts have been fruitless. I've attempted storing the stringified data in an array, crafting functions to assign it to variables, and yet nothing seems to work.

It feels like there's something glaringly obvious that I'm overlooking. Any guidance would be greatly appreciated.

Below is a snippet of what gets printed to the console log:

"type":"FeatureCollection", ... omitted for brevity ... "text":"United States"}]}],"attribution":"NOTICE: © 2022 Mapbox and its suppliers...

Answer №1

data is represented as an object. If you are looking to extract the lat/lng information within the coordinates array, you can achieve this by following these steps.

const data={type:"FeatureCollection",query:["1600","pennsylvania","avenue","washington","dc"],features:[{id:"address.1048737153875776",type:"Feature",place_type:["address"],relevance:.90963,properties:{accuracy:"rooftop"},text:"Pennsylvania Avenue Southeast",place_name:"1600 Pennsylvania Avenue Southeast, Washington, District of Columbia 20003, United States",matching_place_name:"1600 Pennsylvania Avenue Southeast, Washington, DC 20003, United States",center:[-76.982015,38.879235],geometry:{type:"Point",coordinates:[-76.982015,38.879235]},address:"1600",context:[{id:"neighborhood.2918372884011750",text:"Capitol Hill"},{id:"postcode.12587193810898840",text:"20003"},{id:"place.2915387490246050",wikidata:"Q61",text:"Washington"},{id:"region.14064402149979320",short_code:"US-DC",wikidata:"Q3551781",text:"District of Columbia"},{id:"country.14135384517372290",wikidata:"Q30",short_code:"us",text:"United States"}]}]};

// Extract the `coordinates` property from the first element in the `features` array
// and then destructure the lat/lng values from it.
const { coordinates } = data.features[0].geometry;
const [lat, lng] = coordinates;

console.log(lat, lng);

For more information, refer to the following documentation:

Answer №2

When working with response.json() in JavaScript, you can handle the data in various ways. For example, you could log it to the console as shown below. However, you also have the option to store it in a database using an ajax call or present it in a HTML table for better visualization.

const response = fetch(myURL)
    .then(response => {
        const responseObject = response.json();
        const features = responseObject.features;        
        for (let i = 0; i < features.length; i++) {
            const coords = responseObject.features[i].geometry.coordinates;
            console.log(`${features.id} Latitude = ${coords[0]} Longitude = ${coords[1]}`);
        }
    });

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

ReactJS tweet screenshot capture

Currently seeking a solution to capture a tweet screenshot, store it in a PostgreSQL database, and display it on my ReactJS webpage using Typescript. I have been utilizing react-tweet-embed for displaying the tweet, but now I require a method to save the i ...

Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes. However, upon running the script, I noticed that all calculat ...

AngularJS directive does not trigger when switching tabs or scrolling pages

I came across a solution to display a placeholder image before the real image fully loads while browsing online here. I implemented the code provided in the accepted answer on my page, where I have two tabs using `ion-slide-box` for tab selection. Each tab ...

Setting bootstrap datetimepicker values dynamically from a variable

I'm trying to utilize the inline bootstrap datetimepicker from At the moment, it opens in a popup window after the user selects a date/time from a table on another page. My goal is to pass the date/time from that page into datetimepicker and have it ...

Unable to view Google Map markers within my XPath elements while using Selenium?

Looking to extract data from a Google Maps applet. The specific page can be found here: You can click on items on the map to view displayed information. While typical Google Maps show marker elements, I cannot see them on the provided link when inspecti ...

What is the best way for me to show comments beneath all of my posts?

Currently, I am facing an issue with my application where I need to retrieve comments from posts. I am unsure of the best approach to tackle this problem. The existing system only displays posts that have comments, but it shows only a single comment inste ...

The noclose feature in Twitter Bootstrap is malfunctioning when placed within a div

I have a PHP page named a.php that contains the following code: <ul class="dropdown-menu noclose"> This code functions correctly, preventing the drop-down menu from closing until the user clicks outside the box. However, when I load the entire a.p ...

Activate the toggle menu

Hi there! I'm currently working on a menu and I want the clicked item to become active, switching the active state to another item when clicked. However, my current implementation is not working as expected. Any assistance would be greatly appreciated ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Is there a method in Next.js for relocating the .env file to a location external to the application folder?

Currently, I am developing a project that incorporates a Next.js application with the .env file stored in the root directory of the project. Is there a way to configure Next.js to search for the .env file in a location other than the app's root folde ...

How can I include a JSON object in an angularjs $scope variable?

How can I effectively inject my JSON Object into my angular $scope during the create() function? Sample HTML: <input type="text" class="title" placeholder="hold" ng-model="formData.text"/> <input type="text" class="desc" placeholder="description ...

What is the best way to deactivate unclicked href links within a loop?

Looking at the template image, my goal is to disable all links that were not clicked when one of the links from 'number1' to 'number3' is clicked. For example, if 'number2' is clicked, then 'number1' and 'number ...

Discover the method for two form fields to submit data to a distant page, located two pages away

Currently, I'm trying to figure out the best approach for having two fields submitted to a page that is located two pages away. To provide more context, let me elaborate on the situation. On the initial page, there will be two fields - workshop title ...

What could be causing the error in sending JSON data from JavaScript to Flask?

Check out this cool javascript code snippet I wrote: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type=text/javascript> $(function() { $.ajax({ type: 'PO ...

Pug template syntax for importing JavaScript files with links

My Programming Dilemma In my NodeJS webserver setup, I use Express and Pug to serve HTML and JavaScript files. Here's a snippet of how it looks: index.pug html head title Hello body h1 Hello World! script(src='s ...

Deleting elements in an array that have a last digit of 1 - how is it done

I am struggling to remove array elements with a name field that ends in 1. Given Input: { "foo": "bar", "data": { "code": "abc123", "items": [ { "name": "exp1" }, { "name": "exp2" }, { "na ...

Modifying the HTML <select> element with JavaScript

[resolved] I'm encountering an issue with the code below that is supposed to dynamically change the options in a second drop-down menu based on the selection made in the first menu. I've tried to troubleshoot the problem but haven't been suc ...

Experimenting with Vuejs by testing a function that delivers a Promise upon the execution of the "Created" hook

In my Vuejs application, I have the following script written in Typescript: import { Foo, FooRepository } from "./foo"; import Vue from 'vue'; import Component from 'vue-class-component'; import { Promise } from "bluebird"; @Component ...

Transferring information about service events to a controller in Angular

I am facing an issue with some audio elements in my service that listen for the "ended" event. I am looking for a way to pass this message to an angular controller. Currently, my service code looks like this: Audio.addEventListener "ended", (-> ...

After upgrading to version 4.0.0 of typescript-eslint/parser, why is eslint having trouble recognizing JSX or certain react @types as undefined?"

In a large project built with ReactJs, the eslint rules are based on this specific eslint configuration: const DONT_WARN_CI = process.env.NODE_ENV === 'production' ? 0 : 1 module.exports = { ... After upgrading the library "@typescript-es ...