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

Ways to display a different div when clicking on a div?

Good afternoon, I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue. My problem involves a div with the class .title3. I want another div with the class .Content ...

Ways to Deduct 10 Days from a Date using JavaScript

After receiving some helpful suggestions, I managed to solve my date issue by using moment.js. Here is the snippet of code where I implemented moment.js: var preorderdate = moment(date).subtract('days',10).format('MMMM D, YYYY'); var r ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

What is the best way to eliminate the occurrence of the word 'undefined' from the cycle output?

Can anyone assist with solving this issue? The webpage on JSFIDDLE displays 4 news containers, but an 'undefined' string appears before the first news container. I am looking to remove that 'undefined' string. Here is the HTML code: ...

execute the function whenever the variable undergoes a change

<script> function updateVariable(value){ document.getElementById("demo").innerHTML=value; } </script> Script to update variable on click <?php $numbers=array(0,1,2,3,4,5); $count=sizeof($numbers); echo'<div class="navbox"> ...

Do I need to recompile anything after making changes to a node module in my vue.js project in order for the modifications to take effect? The updates are not appearing as expected

Currently tackling a Vue.js project and came across an issue with the Bootstrap-vue module that I would like to remove. After locating the section in the module responsible for this behavior, I commented it out. But strangely, the changes are not showing ...

Is there a way to use Node.js to automatically redirect any random string paths back to the main home page?

Is there a way to configure my basic Node.js server to use simple paths instead of query strings for user session IDs? For instance, can I make domain.com/GH34DG2 function the same as domain.com within my web app? This format seems more visually appealing ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

I'm having an issue where I'm trying to post form data using AJAX, but for some reason, the form continues to submit and refresh the page. Can anyone

Recently, I have been working on a small and simple chat application using mainly JQuery and AJAX technologies. Below is the HTML form I have created for this chat application: <form class="chat_form" method="post" id="chat_form" autocomplete="off"> ...

Using Vue: Save user information in the Vuex store prior to registration

Hello fellow members of the Stackoverflow Community, I am currently working on a Vue.js application that involves user registration. The registration process is divided into three components: Register 1 (email, password), Register 2 (personal information) ...

Refreshing issue: Model change in child page not updating view correctly (Ionic & Angular)

I am currently working with Ionic 3.20 and Angular 5.2.9, encountering an issue with content refreshing after a model change. Despite being new to this, I sense that I might be overlooking something fundamental. Within my view, I have the following elemen ...

Issues with Vuejs3 Pagination Functionality Leading to Errors

Having trouble with implementing pagination? Make sure to limit to 10 pages using `_limit` with `params=ref`. I attempted to set up pagination from axios to params by defining the first page as 1, but unfortunately, the number is not being displayed. No er ...

Seeking a jQuery tooltip plugin that offers support for inline popups similar to overLib

Let's dive into the code: <form name='form 1' action='$action'> input tags <table> some tr tags along with td tags and after some lines in the same table under a td tag <td> <a href="javascript:void(0);" oncli ...

Having trouble receiving a JSON array after making an Ajax request

I have read through previous posts on this issue, but I still can't seem to figure it out. Hopefully, someone here can help me solve this problem. My challenge lies in retrieving an array, which I have encoded in json, from a PHP script and passing i ...

Interacting with Vue3 List Items by Manipulating the HTML DOM

I am currently using Vue 3 and I have a requirement to manipulate a specific list item when a button is clicked. Below is the HTML code snippet: <socialDiv v-for="(follower, i) in followerList" :key="follower.id" :ref="el => ...

Is there a more efficient approach to streamline Javascript code similar to the chaining method used in JQuery?

When working with jQuery, it's possible to streamline the code by running multiple methods in a single statement: $("#p1").css("color", "red").html("Hello world!").attr("class","democlass"); But how can this be accomplished in Javascript? document. ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

Access the extended controller and call the core controller function without directly interacting with the core controller

i have a core controller that contains an array called vm.validationTypes with only 2 objects. I need to add 3 or 4 more objects to this array. to achieve this, i created another controller by extending the core controller: // CustomValidation angular.m ...

Problem with Bootstrap-slider not loading correctly

I seem to be facing an issue with selecting DOM elements that are part of bootstrap-slider. When I try to target them with events like click, nothing happens. All events work fine when the page is refreshed. What could be causing this problem? $(document ...