Extract particular information from the JSON reply

When working with a JSON response in JavaScript, I use the following code to convert it to a string:

var myObject = JSON.stringify(data);

Although this code successfully prints out the results, I am having trouble extracting specific data such as myObject.route.locationSequence[1] or myObject.route.distance. Unfortunately, neither of these seem to work as expected. The JSON response I am working with is shown below.

{
    "route": {
        "hasTollRoad": false,
        "computedWaypoints": [],
        "fuelUsed": 5.67,
        "hasUnpaved": false,
        "hasHighway": true,
        "realTime": -1,
        "boundingBox": {
        "ul": {
        "lng": -77.863792,
        "lat": 40.811218
        },
        "lr": {
        "lng": -76.30574,
        "lat": 39.962482
        }
        },
        "distance": 142.909,
        "time": 9872,
        "locationSequence": [
        0,
        2,
        1,
        3
        ]
    }
}

Answer №1

When you receive the JSON response, avoid doing this:

JSON.stringify(data)

Instead, just access the locationSequence at index 1 like this: data.route.locationSequence[1]

See it in action on this Fiddle

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

Loading tabs dynamically in Angular 2 based on header click event

I successfully created a custom tab component using Angular 2, and it is functioning well with the following usage: <us-tab-verticle> <vtab-content [tabTitle]="'Basic Information'"><basic-info> </basic-info></vtab- ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

What is the reason behind Next.js inability to import files within a directory?

Error: Module not found - Unable to locate 'components/layout' in nextjs-blog/pages/posts > 1 | import Layout from 'components/layout' 2 | import Link from 'next/link' 3 | import Head from 'next/head' I' ...

Struggling with JSON mapping using Jackson?

Task at hand: Mapping the JSON data provided below [{"id":7346,"name":"The Legend of Zelda: Breath of the Wild","cover":{"url":"//images.igdb.com/igdb/image/upload/t_thumb/jk9el4ksl4c7qwaex2y5.jpg","cloudinary_id":"jk9el4ksl4c7qwaex2y5","width":2709,"heig ...

Error encountered in PHP array foreach loop when outputting MySQL query: "illegal offset" and "invalid argument" exceptions.printStackTrace()"

To simplify this explanation, I've condensed the example code. I understand where the issue lies - I just need help using a foreach loop to display the results of my MySQL query. Here is an example array structure: $thetablestructure = array( array ...

Iterate over the contents within the div tag

I need help with looping through the data in this specific div container. My goal is to extract row by row data from it. <div id="result" runat=server> <div id="gvResult" class="RowGroup"> <div class="Row RowBg" tabindex="99"> ...

Is it possible to trigger the setState() function of a parent component when a child component is clicked?

Hey there, I'm a new developer diving into the world of Reactjs. I've been working on setting up a Todo app but struggling to configure it just right. My main challenge is getting a button to add items to the list when submitted. I think I'm ...

The revalidation feature in Next.js' getStaticProps function does not seem to be

https://i.stack.imgur.com/vnNMQ.png I have a question regarding my use of the getStaticProps function in index.js. I am trying to ensure that my API call runs every 60 seconds when a user visits my page, but I am experiencing issues with revalidate not wo ...

Sharing data in JavaScript functions

In order to use certain variables in two separate functions, there are some considerations to keep in mind. The first function is responsible for calculating and displaying a conjugated verb using these variables. The second function checks the user's ...

Guide to retrieving data from Google Books API with GSON and Jsoup

I'm a new user here and I've been attempting to retrieve titles and authors using the Google API by providing an ISBN. Below is the code snippet I used: try { Document docKb = Jsoup.connect("https://www.googleapis.com/books/v1/volumes?q ...

Tips for concealing the "maxlength" attribute in HTML

Here is the code snippet I currently use on a signup and login form to restrict users from entering more than a specified number of characters: $( "#limit1" ).attr('maxlength','11').on('input', function() { if ($(this).val(). ...

What steps should I take to set up a personalized prompt for user input in AngularJS?

After setting up the UI and scope variables, I am faced with a task that requires the function to only continue when either the left or right button is clicked (meaning $scope.isLeft or $scope.isRight will be true). This behavior is akin to how a regular J ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...

Guide on incorporating botframework into a mobile application...?

Recently, I developed a chatbot utilizing the MS bot framework in Nodejs. To display the chatbot in an HTML format without iframes, I incorporated a React Component from the link provided at https://github.com/Microsoft/BotFramework-WebChat. At this point, ...

Iterating over an array of lists to tally the elements

I've been struggling to count the number of objects in an array using JavaScript. Below is the array I'm trying to work with: <script> var arr = [ {"gateways":["ccu1"],"manufacturer":["homematic"],"ir":["ir_no"],"ip":["ip_cam", ...

Can side effects be safely incorporated within the callback of the useState hook?

Consider this scenario: const [value, setValue] = useState(false); const setSomething = (val) => { setValue((prev) => { fn(); dispatch(action); // or any other side effect return prev + val; }); }; Is it acceptable and in line with ...

"Integrating Laravel 5.4 Backend with Angular 5 Frontend: A Step-by-Step

Currently, I am immersed in a project that involves creating a frontend using Angular 5 and backend business logic using Laravel 5.4 with MySQL Database. As someone new to this technology stack, I find myself grappling with establishing the data flow conne ...

The preflight response does not allow the access-control-request-methods request header field due to restrictions set in the access-control-allow-

I'm facing CORS issues while trying to make a POST request from my website to a remote server. Despite searching online, I couldn't find a solution that fits my specific problem. Below are the parameters for my ajax request: var params = { ...

Exploring the world of Vue.js object mapping

I currently have the following object: data: () => ({ customer: { item: { name: undefined }} }) This object is being used in the template as follows: <v-number separator="." decimal="2" ...

The UI router experiences a crash and requires a refresh after precisely six clicks

Whenever the following sequence of events occurs, my application seems to malfunction. Upon clicking on a user and assigning them a role, the page refreshes. A separate GET request retrieves a list of all users currently in the class. After selecting ex ...