What is the best way to fetch the data from this API?

function fetchCoinPrice(coinName) {
  return axios
    .get(
      `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinName}&tsyms=EUR`
    ).then((response) => (response.data[coinName]["EUR"]));

The JSON response for the coin "BTC" is: { "BTC": { "EUR": 8226.43 }} and the function returns the price as a promise.

How can I store the price value (8226.43) in a variable?

Answer №1

Give this code a try. It should work perfectly for your needs.

getCoinPrice(coinName: string) {
    return this._http
    .get(
      `https://min-api.cryptocompare.com/data/pricemulti?fsyms=${coinName}&tsyms=EUR`
  ).pipe(map((result) => (result.BTC.EUR)));

If you want to learn more about accessing objects and their values, check out this resource.

For a comprehensive explanation on working with objects in JavaScript, refer to this link.

See the example below:

Here is a demonstration of how you can retrieve the desired value by accessing objects using a dot .

//Your results
var result = JSON.parse('{"BTC":{"EUR":8226.43}}');

//This will print out 8226.43
console.log(result.BTC.EUR)

Answer №2

Retrieve the value of

result[coinName]["EUR"]

Answer №3

Based on the data you are seeing, the value for {"BTC":{"EUR":8226.43}} is associated with the coinName BTC. To extract the value of 8226.43 from this data:

Therefore, coinName = 'BTC' & observableResult = {"BTC":{"EUR":8226.43}}

If your goal is to retrieve the value based on the coinName, you can use the following method, as the coinName (BTC) serves as the key in the observableResult object.

observableResult[coinName] // This will yield {EUR: 8226.43}

As a result, observableResult[coinName].EUR will give you 8226.43

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

Error: The "toString" property of an undefined variable cannot be read in uploadify

I'm having trouble with uploadify and trying to debug the issue. When attempting to use uploadify in Chrome, I encounter the following error: Uncaught TypeError: Cannot read property 'toString' of undefined Below is my html code: <li ...

The mat-select function is malfunctioning and failing to select any options

I am facing an issue with a form that includes a mat-select field. Even though I initialize this field with values fetched from the backend using an API call, the mat-select is not able to select any values from the available options. Despite trying variou ...

Availability of variables and declaration of functions

I'm having trouble accessing a variable in my Angular project. I am new to this, so please bear with me. Here's an overview of my project: app.component.html: <div> <ul> <li *ngFor='let var1 of Fcomponent' >{{var1}} ...

What alternatives are there to angular scope functions?

I find angular scope functions challenging to work with due to their lack of a clear contract. They extract parameters from the scope and store results back into the scope, rather than explicitly defining function parameters and returning a result. Conside ...

Is it possible to efficiently utilize Map/Set in TypeScript/JavaScript when working with objects?

I'm currently transitioning from Java to TypeScript and I've encountered an issue with working with objects in hashmaps and hashsets. In Java, I would simply override the hashCode method to easily manipulate these data structures. Is there a simi ...

Ways to pass JavaScript variables to a Python script

Hey there! I'm currently facing an issue with retrieving variables from JS to use in my python code. Despite trying methods like AJAX and JQuery, I haven't had much success yet. It's possible that I'm missing something crucial in the pr ...

Is there a way to specify the dimensions of the canvas in my image editing software based on the user-input

Here is the code and link for my unique image editor. I would like to allow users to enter the desired width and height of the selection area. For example, if a user enters a width of 300 and height of 200, the selection size will adjust accordingly. Addit ...

Continual dark mode throughout page navigation with the ability to switch between light and dark modes

I've been experimenting with creating a persistent dark mode feature for web pages. My goal is to remember the user's preference as they navigate between pages. Additionally, I included a toggle button for switching between dark and light modes t ...

Can you explain the meaning of the code provided below?

I'm having trouble understanding the functionality of this code snippet: .bind(this); (I copied it from the Zurb Foundation dropdown plugin) .on('mouseleave.fndtn.dropdown', '[data-dropdown], [data-dropdown-content]', function ( ...

Issue with Flask-Cors in Nuxt with Flask and JWT authentication implementation

I have exhausted all the available solutions to my issue, but I still can't seem to pinpoint the problem. Despite trying every solution out there, nothing seems to be of any help. Every time I make a request, the browser blocks it due to CORS Policy ...

Dynamic field validation using jQuery

I am currently developing a wizard feature that retrieves employees dynamically from the backend. The employee table is created with a radio input field and then inserted into my HTML code: $.ajax({ method: "get", url: '/fetchEmployees/' ...

Can you tell me the appropriate type for handling file input events?

Using Vue, I have a simple file input with a change listener that triggers the function below <script setup lang="ts"> function handleSelectedFiles(event: Event) { const fileInputElement = event.target as HTMLInputElement; if (!fileInp ...

The React Query devtools are failing to display

I am currently working on a project using React Query, but for some reason, the DevTools icon is not appearing on my screen. I have checked the console for errors, but there are none. I am following a tutorial on YouTube to help me with this. Here is a sn ...

How to exclude specific {} from TypeScript union without affecting other types

Consider the following union type: type T = {} | ({ some: number } & { any: string }) If you want to narrow this type to the latter, simply excluding the empty object won't work: type WithEntries = Exclude<T, {}> This will result in neve ...

How do I determine in Angular (2+) when all child components have been initialized from the parent component?

Is there a lifecycle hook named "ngAfterAllChildrenInit" that can be used because ngAfterViewInit is called before the ngOninit of the children? I am currently trying to find a solution that avoids using setTimeOut or emitting events from all of the child ...

How can you provide arguments to a mock function?

While using jest for unit testing, I am encountering the following line of code: jest.mock('../../requestBuilder'); In my project folder, there is a __mocks__ subfolder where I have stored my mock requestBuilder.js file. The jest unit test i ...

After updating to the latest npm version, the NodeJS server continues to display the error message "Upgrade Required" when loading pages

After developing a Node project using NodeJS version 5.4.x and NPM version 3.3.12 on Windows, I encountered an issue where the project throws an "Upgrade Required" message (HTTP Error code - 426) upon loading the page after some time of inactivity. To add ...

conditionally trigger one observable in rxjs before the other

I am in need of assistance or guidance regarding a challenge I am facing with rxjs that I cannot seem to resolve. In essence, my goal is to trigger an observable and complete it before the original one is triggered. Scenario: I am currently working on a ...

Utilizing HTML5 history instead of hash URLs to preserve the user's browsing history

Our application is a single page that dynamically loads results based on query strings. The query string format we use is as follows: ?city=Delhi&pn=1 Within the SPA, there are different sections displayed on the same page. As users navigate through ...

Get the ability to overlay text onto an image by using jQuery for downloading

Currently, I am facing an issue with an online photo editor in my project. The problem is that I am unable to download the image after adding and editing text on it. The texts added are editable but the image cannot be downloaded after the changes. I nee ...