Retrieve the data object in VueJS

(Regarding a currency conversion tool)

In order to accurately convert currencies, I am looking to access an object structured like this:

rates:
  AUD: 1.708562
  SGD: 1.546211

When retrieving these rates from an API, they are not always in the desired order. For example, if I request the conversion from USD to GBP, GBP may appear before USD. Therefore, I need a method to retrieve the values based on the requested symbols.

I attempted the following approaches:

const from = res.rates.this.convertFrom.symbol;
// -----AND-----
const fromSymbol = this.convertFrom.symbol;
const from = res.rates.fromSymbol.toString();

Unfortunately, none of these methods yielded the desired results.

For more information, you can visit the codesandbox

Note: The value of this.convertFrom.symbol corresponds to the user input, which in this case is symbol: 'SGD'

Answer №1

Essentially, the data setup you have is as follows:

convertFrom: {
    currency: "GBP: British Pounds",
    symbol: "",
    amount: 0
},
convertTo: {
    currency: "USD: United States Dollar",
    symbol: "",
    amount: 0
}

In the convert() method, the currency symbols are set like so:

this.convertFrom.symbol = this.convertFrom.currency.toString().split(":")[0];
this.convertTo.symbol = this.convertTo.currency.toString().split(":")[0];

As a result, the values of convertFrom.symbol and convertTo.symbol become:

this.convertFrom.symbol => "GBP"
this.convertTo.symbol => "USD"

You've also noted that the fetch response structure looks like this:

{
    "success": true,
    "base": "EUR",
    "rates": {
        "GBP": 0.869339,
        "USD": 1.0875
    }
}

Since the keys in the object rates are dynamic, we must use bracket notation to access them like so:

const from = res.rates[this.convertFrom.symbol]
const to = res.rates[this.convertTo.symbol]

Check out the code snippet for a demonstration:

const res = {
  "success": true,
  "base": "EUR",
  "rates": {
    "GBP": 0.869339,
    "USD": 1.0875
  }
}

const data = {
  convertFrom: { symbol: "GBP" },
  convertTo: { symbol: "USD" }
}

const from = res.rates[data.convertFrom.symbol];
const to = res.rates[data.convertTo.symbol];

console.log('From:\t', from)
console.log('To:\t', to)

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

CSRF fails to execute during the initial post submission

This is my first time dealing with CSRF and reaching out to Stack Overflow for the first time. After struggling through the configuration, I finally managed to get it working almost perfectly. However, I ran into an issue where if I open a bookmarked page ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

Unforeseen SyntaxError: Unexpected symbol detected

Encountering an issue while attempting to send raw data as parameters in express. Specifically, there is an error occurring at the 'fields' variable... function getWithQuery(req,res){ console.log(req.params); var query = {name: new RegEx ...

Is there a way to automatically scroll the parent page's top when the user navigates within an iframe?

We are encountering an issue with the loading of the iFrame. When the iFrame loads on the client's page, we notice that the page location jumps around and, in most cases, the page focus is lower down the page. This requires users to scroll up to view ...

Save a canvas image directly to your WordPress media library or server

I'm working on integrating a feature that enables users to save a png created on a canvas element into the WordPress media library, or at least onto the server (which is an initial step before sharing the image on Facebook, as it requires a valid imag ...

What are the potential drawbacks of relying heavily on socket.io for handling most requests versus using it primarily for pushing data to clients?

Is it advisable to switch AJAX routes (called with $.Ajax in jquery) like: GET /animals GET /animals/[id] POST /animals To socket.io events (event bound on client and server for client response): emit("animals:read") emit("animals:read", {id:asdasd}) ...

Switching effortlessly between Fixed and Relative positioning

As I work on creating a unique scrolling experience, I aim to have elements stop at specific points and animate before returning to normal scroll behavior once the user reaches the final point of the page. Essentially, when div X reaches the middle of the ...

Unexpected outcomes when trying to sort and paginate React-Table

Experiencing unexpected results with react-table integration for pagination and sorting. Merged examples from the react-table repository. Encountering an issue where table hooks reset the page index on re-render, causing fetchData to be called twice during ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

Selecting elements dynamically with JQuery

Trying to use a jQuery selector within plugin code created by a 3rd party has proved difficult. When hardcoded, it works fine; however, when attempting to use variables for dynamic selection, the object cannot be found. The lack of id handles in the CSS c ...

Guide To Implementing vue-color Into Your NuxtJs Project

Could someone assist me with importing vue-color into my project? I have tried to import and render the component using the following code: <template> <div class="helloWorld"> <Chrome /> </div> </template> & ...

I am experiencing an issue where the Axios configuration does not display the OnUploadProgress on my response

I have been attempting to track the progress of file uploads from the front end, but I am encountering an issue where the onUploadProgress is not being received in the configuration catch. This problem arises as I am relatively new to using Axios. axios({ ...

Transferring checkbox data to Bootstrap modals and dynamically summoning specific div modals using their unique identifiers

I have been trying to populate the checkbox values into corresponding modal divs based on button clicks, but I am facing difficulties in achieving it. Desired outcome: The buttons should trigger the display of selected checkbox values in their respective ...

Unforeseen alterations in value occur in JavaScript when converting to JSON format

Having trouble generating a gantt chart from a JSON string, specifically with parsing the JSON string into a JSON object. I have a variable myString containing a JSON string that looks like this: {"c": [{"v": "496"}, {"v": "Task name 1"}, {"v": "9, "}, { ...

Using V-model binding in Vue always resets the content of text inputs

I am facing an issue with a Text Input that is filled based on a string stored in cookies, similar to a Remember me feature. When I bind the value of the input to the cookie using :value, I am unable to type a new value even if there is no cookie being sto ...

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

Calculate the sum in real-time using JavaScript

How can I dynamically compute the sum of subtotals without encountering the following error? document.getElementById("item_subtotal[" + cnt + "]") is null Below is my JavaScript code: function calculateTotalAll(numitems) { var cnt = 1; var tot ...

What is the best way to access form data in React using a React.FormEvent<HTMLFormElement>?

I am looking for a way to retrieve the values entered in a <form> element when a user submits the form. I want to avoid using an onChange listener and storing the values in the state. Is there a different approach I can take? login.tsx ... interfa ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...