如何从cryptocompare返回的嵌套对象中获取CHANGEPCT24HOUR值
Hey there! Let's figure out how to grab that CHANGEPCT24HOUR value from the nested object returned by the Cryptocompare npm package—this is simpler than you might think, and I'll cover both direct access (for fixed currency pairs) and dynamic traversal (in case you're working with variable pairs).
Direct Access (Best for Known Currency Pairs)
Since you're explicitly requesting ETH to USD, the structure of the response object is predictable. You can directly chain the property names to get the value without any loops:
const cc = require('cryptocompare'); cc.priceFull('ETH', 'USD') .then(prices => { // Use dot notation for clean, direct access const hourlyChangePct = prices.ETH.USD.CHANGEPCT24HOUR; console.log('24-hour Change Percentage:', hourlyChangePct); // Outputs 2.958072383879366 // Alternatively, use bracket notation (useful if keys are stored in variables) // const hourlyChangePct = prices['ETH']['USD']['CHANGEPCT24HOUR']; }) .catch(console.error);
This works because you know exactly what keys exist in the response—ETH is the base currency key, USD is the quote currency key, and CHANGEPCT24HOUR is the specific metric you want.
Dynamic Traversal (For Variable Currency Pairs)
If you're working with dynamic currency pairs (e.g., letting users select different pairs), you can use loops to traverse the nested object. It sounds like you tried for-in before—here's how to do it correctly by nesting loops to match the object's structure:
const cc = require('cryptocompare'); cc.priceFull('ETH', 'USD') .then(prices => { // First loop through the base currencies (e.g., ETH) for (const baseCurrency in prices) { if (prices.hasOwnProperty(baseCurrency)) { // Skip inherited object properties const quoteCurrencyData = prices[baseCurrency]; // Then loop through the quote currencies (e.g., USD) for (const quoteCurrency in quoteCurrencyData) { if (quoteCurrencyData.hasOwnProperty(quoteCurrency)) { const marketData = quoteCurrencyData[quoteCurrency]; const hourlyChangePct = marketData.CHANGEPCT24HOUR; console.log(`24h Change % for ${baseCurrency}/${quoteCurrency}:`, hourlyChangePct); } } } } }) .catch(console.error);
Or if you prefer a more modern approach with Object.entries (which returns key-value pairs directly for cleaner code):
const cc = require('cryptocompare'); cc.priceFull('ETH', 'USD') .then(prices => { // Iterate over base currency entries Object.entries(prices).forEach(([baseCurrency, quoteData]) => { // Iterate over quote currency entries Object.entries(quoteData).forEach(([quoteCurrency, marketMetrics]) => { console.log(`${baseCurrency}/${quoteCurrency} 24h Change %:`, marketMetrics.CHANGEPCT24HOUR); }); }); }) .catch(console.error);
The key here is matching the loop nesting to the object's structure—your response has two levels of nesting (base currency → quote currency → metrics), so you need two levels of loops to reach the CHANGEPCT24HOUR value.
内容的提问来源于stack exchange,提问作者mrks

