如何获取API返回的JavaScript命名对象的名称?
OldCrowMine.E9001 from Your API Response Hey there! Let's break down how to grab those miner names (like OldCrowMine.E9001) from your API's returned object—they're actually just the keys (property names) of the top-level object you're getting back.
Step 1: Use Object.keys() to Extract All Keys
The simplest way to get all those names at once is with JavaScript's built-in Object.keys() method. It takes your object as input and returns an array of all its property names.
Let's use your sample data to show how it works:
// Store your API response in a variable const apiResponse = { "OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0}, "OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274} }; // Extract all miner names into an array const minerNames = Object.keys(apiResponse); console.log(minerNames); // Output: ["OldCrowMine.E9001", "OldCrowMine.S9001"]
Step 2: Use Keys to Create New Independent Objects
If you want to loop through each miner name and pair it with its data to create new objects, you have a couple of great options:
Option A: Object.entries() (Clean & Modern)
This method returns an array of [key, value] pairs, making it easy to access both the name and the corresponding data in one go:
for (const [minerName, minerData] of Object.entries(apiResponse)) { // Create your new independent object here const newMinerObject = { name: minerName, ...minerData // Spread the existing miner data into the new object }; console.log(newMinerObject); // Example output for first miner: // { name: "OldCrowMine.E9001", last_share: 1524883404, score: "0.0", ... } }
Option B: for...in Loop
If you prefer a more traditional loop, for...in works too—just make sure to use hasOwnProperty() to avoid inherited properties (though with API responses, this is usually not necessary, it's good practice):
for (const minerName in apiResponse) { if (apiResponse.hasOwnProperty(minerName)) { const minerData = apiResponse[minerName]; const newMinerObject = { name: minerName, ...minerData }; console.log(newMinerObject); } }
Quick Note
Your API returns a single object where each key is a miner identifier, and the value is that miner's data. Unlike arrays (which use numeric indexes), objects use custom keys like OldCrowMine.E9001—that's why Object.keys() is exactly what you need here.
内容的提问来源于stack exchange,提问作者SevilNatas

