You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JavaScript对象中"Exchange Rate"的18.52005000值赋值给变量?

Extracting Exchange Rate from JavaScript Object

Hey there! Since you've got basic JavaScript under your belt, grabbing that exchange rate value is straightforward—let's walk through it based on common API response structures you might be dealing with.

Scenario 1: Directly Accessible Key

If your API returns a flat object where the "Exchange Rate" key is at the top level, like this:

// Example API response object
const exchangeData = {
  "Base Currency": "USD",
  "Target Currency": "THB",
  "Exchange Rate": "18.52005000"
};

You can use square bracket notation (required for keys with spaces) to extract the value, then convert it to a number (since API responses often return numeric values as strings, which you'll need for calculations):

// Extract and convert the exchange rate to a number
const exchangeRate = Number(exchangeData["Exchange Rate"]);

// Alternatively, use parseFloat if you want explicit floating-point handling
const exchangeRate = parseFloat(exchangeData["Exchange Rate"]);

Scenario 2: Nested Object Structure

Many APIs wrap data in nested objects (like under a data or conversion key). For example:

// Example nested API response
const apiResponse = {
  status: "success",
  payload: {
    conversionDetails: {
      "Base Currency": "USD",
      "Target Currency": "THB",
      "Exchange Rate": "18.52005000"
    }
  }
};

Just traverse the object layers step by step, again using square brackets for the spaced key:

// Traverse nested properties and convert to number
const exchangeRate = Number(apiResponse.payload.conversionDetails["Exchange Rate"]);

To avoid errors if any intermediate property might be missing (like if the API returns an error), use the optional chaining operator (?.):

// Safe access with optional chaining (prevents crashes if a property is undefined)
const exchangeRate = Number(apiResponse?.payload?.conversionDetails?.["Exchange Rate"]);

If the rate doesn't exist, this will set exchangeRate to NaN—you can add a quick check (like if (!isNaN(exchangeRate))) to handle that case!

Quick Tip

If you're unsure about the exact structure of your API response, log it to the console first:

console.log(exchangeData); // Or whatever variable holds your API data

This will let you inspect the object and confirm the exact path to the "Exchange Rate" key.

内容的提问来源于stack exchange,提问作者Jobbie Daddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:59:14