含数字键索引的数组处理咨询:附加密货币数组结构示例
Hey there! Let's tackle this array with numeric/special character keys you've got. I see your objects have properties like 24h_volume_usd which can be a bit tricky to handle directly in some cases—here are a few solid solutions tailored to your use case:
When dealing with keys that start with numbers or contain special characters (like hyphens), you can't use the dot notation (e.g., item.24h_volume_usd will throw an error). Instead, use bracket notation to access these properties:
const cryptoData = [ { "id": "bitcoin", "name": "Bitcoin", "symbol": "BTC", "24h_volume_usd": "5106040000.0", /* ... rest of properties */ } ]; // Access the 24h_volume_usd property safely const dailyVolume = cryptoData[0]["24h_volume_usd"]; console.log(dailyVolume); // Output: "5106040000.0"
This works for any key, regardless of its format.
If you want to avoid typing bracket notation every time, you can transform the array to rename these special keys to camelCase or more standard identifiers. This also lets you convert string-based values (like prices or timestamps) to proper data types:
const formattedCryptoData = cryptoData.map(item => { return { id: item.id, name: item.name, symbol: item.symbol, rank: parseInt(item.rank), priceUsd: parseFloat(item.price_usd), // Rename the numeric key to a camelCase alternative volume24hUsd: parseFloat(item["24h_volume_usd"]), marketCapUsd: parseFloat(item.market_cap_usd), percentChange1h: parseFloat(item.percent_change_1h), lastUpdated: new Date(parseInt(item.last_updated) * 1000) // Add other transformed properties as needed }; }); // Now you can use dot notation for all properties console.log(formattedCryptoData[0].volume24hUsd); // Output: 5106040000.0
If you need to loop through every property in the objects (without knowing the key names upfront), use Object.keys() or Object.entries() to ensure you don't miss the numeric/special keys:
const firstCrypto = cryptoData[0]; // Loop through keys with Object.keys() Object.keys(firstCrypto).forEach(key => { console.log(`Property: ${key}, Value: ${firstCrypto[key]}`); }); // Or use Object.entries() for key-value pairs directly for (const [key, value] of Object.entries(firstCrypto)) { console.log(`${key}: ${value}`); }
When embedding these values in template strings, stick with bracket notation inside the template:
console.log(`Bitcoin's 24-hour trading volume: ${cryptoData[0]["24h_volume_usd"]} USD`);
内容的提问来源于stack exchange,提问作者Kamalpreet Singh

