NodeJS+MySQL场景下:遍历哈希数组并获取哈希键的方法
Hey there! When you query MySQL using Node.js (with packages like mysql or mysql2), the result set comes back as an array of RowDataPacket objects. Don't let the fancy name throw you off—these are just regular JavaScript objects under the hood, so you can use all standard JS object methods to work with them.
Step 1: Extract Keys from a Single RowDataPacket
To get the keys from one of these objects, use Object.keys()—it's the simplest and most standard way. Here's how:
// Assume your query result is stored in the 'result' variable const firstRow = result[0]; const rowKeys = Object.keys(firstRow); console.log(rowKeys); // Output: ['FieldName', 'Input']
Step 2: Traverse the Entire Array to Get Keys
Depending on your needs, there are a few ways to loop through the array and extract keys:
Option 1: Collect Keys for Every Row
If you want an array where each element is the list of keys from the corresponding row in your result set, use Array.map():
const allRowKeys = result.map(row => Object.keys(row)); // Result: [['FieldName','Input'], ['FieldName','Input'], ...]
Option 2: Gather All Unique Keys Across Rows
If you need a list of all distinct keys present in any row (useful if rows might have different fields), use a Set to avoid duplicates:
const uniqueKeys = new Set(); result.forEach(row => { Object.keys(row).forEach(key => uniqueKeys.add(key)); }); const uniqueKeysArray = Array.from(uniqueKeys); console.log(uniqueKeysArray); // Output: ['FieldName', 'Input'] (if all rows have same keys)
Option 3: Traditional For Loop
If you prefer a more explicit loop, a standard for loop works too:
for (let i = 0; i < result.length; i++) { const currentRow = result[i]; const keys = Object.keys(currentRow); console.log(`Row ${i} has keys:`, keys); }
Quick Note on RowDataPacket
You might wonder if you need to convert RowDataPacket to a plain object first. The short answer is no—since RowDataPacket inherits from JavaScript's Object, methods like Object.keys() work directly on it. That said, if you ever want a plain object for other purposes, you can easily do:
const plainObj = {...currentRow};
内容的提问来源于stack exchange,提问作者Karthik Muthu

