Ways to extract information from a JSON object

Could you please assist me in extracting data from a JSON object using JS? Below is the snippet of my code:

  const currency_one = currencyOne.value;
  const currency_two = currencyTwo.value;

  const myHeaders = new Headers();
  myHeaders.append('apikey', API_KEY);

  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
    headers: myHeaders,
  };

  fetch(
    `https://api.apilayer.com/exchangerates_data/convert?to=${currency_one}&from=${currency_two}&amount=${amountOne.value}`,
    requestOptions
  )
    .then((res) => res.text())
    .then((data) => console.log(data))
    .catch((err) => console.log('error', err));
};

The output displayed on the console is as follows:

{
    "success": true,
    "query": {
        "from": "AED",
        "to": "USD",
        "amount": 1
    },
    "info": {
        "timestamp": 1662496624,
        "rate": 0.27225
    },
    "date": "2022-09-06",
    "result": 0.27225
}

I specifically require access to the "result" section only.

Your assistance is greatly appreciated!

Answer №1

In the case that data is already an object, you can retrieve the result using the following line of code:

console.log(data.result);

However, if data happens to be in a string format, you can utilize this snippet:

let parsed = JSON.parse(data);
console.log(parsed.result);

If unsure about the type of data, try running this command:

console.log(typeof data);

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

Unable to set selected property in React Material-UI menu item

One issue I'm facing is setting the selected prop using react mui menu item. In a multiple select menu list, there's a field called allValues that, when clicked, should toggle the selection of all menu items. The code for this functionality looks ...

Identify similarities between two elements within an array, and if specific attributes align, modify the property of the first element

I am facing a challenge with two large arrays in my project. allInventoryItems.length //100,000 objects `allInventoryItems[0] // { name: 'Something', price: 200 } along with currentInventory.length //~250 objects `currentInventory[0] / ...

Tips for updating key names in a JSON file without converting it into a JSON array

I have a script that is designed to swap out a key name in a json file. The current format of the json file looks like this: {json:data1} {json:data2} {json:data3} However, every time I execute my script import json json_data = [] with open('test. ...

Ways to retrieve a class list of a tag located within a div by clicking on the div, rather than the tag itself

I have 2 divs with an a tag and an i tag enclosed within them. I am using an onclick function, but it does not require writing the function itself. You can use something like getting elements on click of this item and then finding a certain class within th ...

Is it possible to execute an npm package without using the npm run command?

Is there a way to initiate the next.js build process directly through the command line without needing to use the package.json file? Can we execute it without relying on npm run? Perhaps running next build in the command line could achieve this instead of ...

Interactive map navigation feature using React.js

Can someone help me figure out how to create a dynamic map with directions/routes? I am currently using the Directions Renderer plugin, but it only shows a static example. I want to generate a route based on user input. Below is the code snippet: /* ...

Ways to address time discrepancies when the countdown skips ahead with each button click (or initiate a countdown reset upon each click)

Every time I click my countdown button, the timer runs normally once. But if I keep clicking it multiple times, it starts skipping time. Here are my codes: <input type="submit" value="Countdown" id="countdown" onclick="countdown_init()" /> <div i ...

What is the process for developing a unique JsonDeserializer in Java?

Within a class C, I have a field Map<A,B> fieldOfC. When attempting to deserialize C using Jackson, an Exception is thrown due to the inability to find a Deserializer for Map's key A. It seems that the solution lies in extending StdJsonDeseriali ...

Is there a way to execute code prior to an element being removed by an *ngIf directive in Angular 13?

I have a form where a specific input is displayed based on the selected option. <form [formGroup]="form" (ngSubmit)="search()"> <div class="row"> <div class="col-4"> <p-dropdown [options]="selec ...

What is the process for activating JavaScript and embedding it into an HTML document?

I am currently utilizing a JavaScript API that contains several functions. How can I incorporate it into an HTML file? One of the functions, "api.ping()", performs well on PowerShell, but I am encountering difficulties with displaying it on an HTML file. ...

How can we effectively use mongoose populate in our codebase?

Hey there, I'm a newbie when it comes to nodejs and mongoose, and I could really use some assistance with mongoose populate. Can someone please help me understand this better? Thanks in Advance! Here are the schemas I'm working with: PropertySch ...

Is there a lack of a feature for automatically shifting to the next input element in dynamically-created HTML?

I have a JavaScript function that is triggered when a user clicks a button: htmlstring = ''+ '<div class="input_holder">'+ '<div class="as_input_holder"><input tabindex="1" class="as_input form-control-sm ...

I am experiencing an issue with PHP JSON not functioning properly. Can someone provide insight into why this

myfile.php header('Content-type: application/json'); echo json_encode( array( 'error' => 'jkfshdkfj hskjdfh skld hf.' ) ); the code above is functioning correctly. however, when it is modified, it no longer works: if( ...

Having trouble with the form parsing not functioning properly

I have been utilizing Express.js along with the body-parser module for form parsing on the server. However, I am facing an issue where the content received appears as an empty object under res.body. This is how my app.js looks: var express = require("exp ...

Problem concerning the Script tag within Javascript coding

This link is supposed to show a Google ad. I've attempted all possible solutions, but it still doesn't seem to be functioning correctly. My suspicion is that the issue lies with the closing script tag - </script>. Could you please copy th ...

Angular Karma encountered an error: TypeError - It is unable to read the property '_id' as it is undefined

Encountering an issue while testing with karma jasmine, the error message appears as... TypeError: Cannot read property '_id' of undefined This is the Component.ts file: import { Component, OnInit } from '@angular/core'; import { ApiSe ...

How can I resolve the issue of using string values for items inside v-autocomplete, but needing them to be numbers in v-model?

I am working with a v-autocomplete component <v-autocomplete v-model="addressRegion" :items="selectLists.regions" item-value="key" item-text="value" ></v-autocomplete> The AddressRegion is curren ...

Create a JavaScript function that generates 100 evenly spaced steps within a given range

I have been struggling to generate steps of 100 between two values, -0.1 and 0.1. Despite trying various methods, I have not yet achieved success. In this code snippet, there is an input range: $('#slider').change(function(){ var val = ($( ...

Changing the map behavior when it is moved in Leaflet

I am currently using Leaflet to design a map that includes a personalized sound layer. Each tile on the map features an <audio> element, and I am exploring methods to adjust the audio playback as the user navigates around the map (specifically by mod ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...