如何将JavaScript对象中"Exchange Rate"的18.52005000值赋值给变量?
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

