Merge two distinct JSON objects obtained through an API request using Javascript

Struggling with my currency conversion project, I'm trying to display JSON response results on my website but can't seem to make it work. The code snippet below,

  .then((response) => {
      return response.json();
    })
    .then((jsonResponse) => {
      let objData = {
        amount: '',
        from: '',
        to: '',
        result: '',
      };
      window.console.log('jsonresponse ==>' + JSON.stringify(jsonResponse));
      let exchangeData = jsonResponse['query'];
      window.console.log('exchangeData==> ' + JSON.stringify(exchangeData))
      objData.amount = exchangeData['amount'];
      objData.from = exchangeData['from'];
      objData.to = exchangeData['to'];
      objData.result = exchangeData['result'];
      this.conversionData = objData;
      window.console.log('objData=' + JSON.stringify(objData));

    }).catch(error => {
      window.console.log('callout error ' + JSON.stringify(error));
    })

  }

}

currently only fetches 'amount', 'from', and 'to' without getting the 'result'. How do I modify it to also include the conversion result? Here is a sample of the JSON data:

{   "info": { "quote": 0.975625, "timestamp": 1669042263 }, 
    "query": { "amount": 5, "from": "USD", "to": "EUR" }, 
    "result": 4.878125, 
    "success": true 
}

The current output retrieves only:

"query": {
    "amount": 5,
    "from": "USD",
    "to": "EUR"

Please guide me on how to retrieve the complete data including the result.

I attempted the following approach that did not yield the desired outcome:</p>
const obj1={"query":[ { "amount":"", "from": "", "to": "" }, ] }; 
const obj2={"result":{}, }; 
const response = JSON.parse(JSON.stringify(obj1)); 
response.query.push(...obj2.result); console.log(response);

Answer №1

It seems like you are searching for the result in the wrong place

objData.result = exchangeData['result'];

where

let exchangeData = jsonResponse['query'];

However, jsonResponse['query'] does not actually include the result.

You should try

objData.result = jsonResponse['result'];

instead.

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

Utilize NodeJS to dynamically alter the text outputted on an HTML page

For educational purposes, I am designing a website where users can sign in by entering their name on the login page. After signing in, they will be redirected to the home page which displays a personalized welcome message using their name. I have included ...

How to arrange JSON data by value in Python

Looking for a way to sort my JSON data in Python either in ascending or descending order based on the values. Here is an example of the JSON data: { "efg": 1, "mnp": 4, "xyz": 3 } The desired output for ascending order would be: { "mnp" ...

What is the reason that prototypes are not passed down through inheritance?

Can anyone shed light on why Validator.js is structured the way it is initialized (as shown in the first code snippet) and the reason behind the inability to call the validate method (as demonstrated in the second snippet)? I am currently experimenting wi ...

Handlers for adjustments not correctly updating values in introduced object

I am facing an issue with a table that displays data fetched from an API and a select dropdown. Whenever a checkbox is selected, the name key along with its value is added to an array object named selectedFields. checkbox = ({ name, isChecked }) => { ...

Tips on accessing the text content of a dt element with prototype

Below is some HTML code that I am working with: <dl> <dt><label>test</label></dt> <dd><input id="someid" type="checkbox" onchange="opConfig.reloadPrice()" class="product-custom-op ...

JavaScript embedded within LD-JSON format

Is it feasible to run JavaScript code within an ld+json script? Like for instance, "window.location.hostname" <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://" + window.location.ho ...

Utilizing Firebase push notifications with multiple google-service.json files within a single Android Studio project

In a scenario where we have a single project but require multiple Firebase push notification and google-server.json files, how can we effectively manage these multiple files within Android Studio? ...

What are the specific files I should modify for HTML/CSS in my Ruby application?

My application was initially created with an introduction from: http://guides.rubyonrails.org/getting_started.html I am now looking to add some color and style through CSS. I have located the JavaScript and CSS files, but I am unsure which file is respons ...

Twitter and JSON outputs with a single line formatting

I am attempting to acquire all tweets that include specific keywords within the Twitter firehose for a single day and save them in a JSON file. Below is the code I am using: import re import twitter import numpy as np import pandas as pd import os import ...

Mongoose documents are set to automatically be deleted after a duration of one month

My goal is to retain a particular document for one month after the client-user deletes it. To achieve this, I have decided to simulate a delete action and display data in the browser. Sample schema: const product = new mongoose.Schema({ --- trash : { ty ...

When checking for a `null` value, the JSON property of Enum type does not respond in

Within my Angular application, I have a straightforward enum known as AlertType. One of the properties in an API response object is of this enum type. Here is an example: export class ScanAlertModel { public alertId: string; public alertType: Aler ...

Using JLinq for Date-Based Filtering of JSON Data

I have been trying to use JLinq for filtering JSON data, but I am facing an issue with filtering by date. Despite attempting different methods, the problem persists. Below is a snippet of my code: //This works jlinq.from(myData) .select(function ...

Using MongoDB and NodeJS to retrieve data from a promise

When I make a request to the database using promises, my goal is to extract the values of "latitude" and "longitude" for all documents and store them in an array. This is how I am currently approaching it: const promises = [ dbo.collection("users").f ...

Tips for gradually increasing numerical values line by line

Plunker. After implementing the Plunker provided above, I noticed that the rowId is increasing with alphabets, as shown below: The component in the Plunker contains buttons labeled with +, ++, and -. When you press the + button, the rowId starts from the ...

Utilize serde_json to extract key information from a JSON dataset and display all the keys in the

Here is a basic example showcasing how to parse JSON data in Rust. After parsing, the question arises on how to identify the keys of a serde_json::Value, such as "name", "age", "phones" in this particular scenario? fn json_h ...

What could be the reason for the mismatch in size between the downloaded file in Express.js and the file size on the server?

My code using express.js is quite simple: app.get("/download", download); and export let download = async (req: Request, res: Response) => { const file = "/tmp/my-file.zip"; res.download(file); } The client-side code is also straightforward: im ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

An unusual problem encountered with JSON and PHP

Is there a specific reason why a JSON string fails to be evaluated (transport.responseText.evalJSON();) on the server but works fine on my local setup? I'm making a simple AJAX request like this: new Ajax.Request( this.saveUrl, { ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

Using prerender.io in conjunction with native Node.js

Currently, I am working on integrating prerender.io into my Angular 1.6.0 application that is being hosted on a Node.js server. The instructions provided in the documentation for setting up the middleware involve using the connect middleware, with a speci ...