如何使用JavaScript从JSON对象中获取键及其对应值
It looks like your parsed data object has a lobby property that holds the key-value pairs you need to access. Here are a few straightforward ways to get each key and its corresponding value:
Method 1: Use Object.entries() (Simplest for Key-Value Pairs)
This method returns an array of [key, value] pairs, making it easy to iterate over both at once:
// Your existing code to parse the data var data = JSON.parse(JSON.stringify(originalData)); console.log(data); // Access the lobby object containing your key-value pairs const lobbyData = data.lobby; // Iterate through each key-value pair for (const [key, value] of Object.entries(lobbyData)) { console.log(`Key: ${key}, Value: ${value}`); // Replace the console log with whatever you need to do with the key/value }
Method 2: Use Object.keys() to Get Keys First
If you prefer to loop through keys and then retrieve their values separately, this works too:
const lobbyData = data.lobby; Object.keys(lobbyData).forEach(key => { const value = lobbyData[key]; console.log(`Key: ${key}, Value: ${value}`); });
Method 3: Collect Pairs into an Array of Objects
If you want to store all key-value pairs in a structured array for later use:
const lobbyData = data.lobby; const keyValueArray = Object.entries(lobbyData).map(([key, value]) => ({ key: key, value: value })); console.log(keyValueArray); // Output will look like: [{key: "8jmb9ca3s04c8el4j5sf0d", value: "AD8BJBkMKCBoYg_qAAAB"}, ...]
Note: Your console output had some formatting quirks (like duplicate lobby: labels and odd characters), but assuming the actual data.lobby is a valid JavaScript object with the keys and values you listed, these methods will work perfectly.
内容的提问来源于stack exchange,提问作者Muhammad Awais




