Home > Software design >  Concatenate two different JSON objects from an API call in Javascript
Concatenate two different JSON objects from an API call in Javascript

Time:11-22

I am working on a currency conversion project trying to get my code to display results from a JSON response on my website and I am not able to do it yet. The code 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));
    })

  }

}

returns only 'amount', 'from' and 'to' and not 'result'. How can I get it to return the result of the conversion. This is the sample JSON

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

For now, my code only returns

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

How can I get it to return

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

I have tried the below and it did not work.

const obj1={"query":[ { "amount":"", "from": "", "to": "" }, ] }; 
const obj2={"result":{}, }; 
const response = JSON.parse(JSON.stringify(obj1)); 
response.query.push(...obj2.result); console.log(response);

CodePudding user response:

You are asking result from the wrong place

objData.result = exchangeData['result'];

where

let exchangeData = jsonResponse['query'];

But jsonResponse['query'] does not contain result.

You should do

objData.result = jsonResponse['result'];

instead.

  • Related