JavaScript中如何合并循环获取的多个对象键数组为单个数组?
Got it, let's break down your problem first: right now, you're reassigning keyes every time inside the loop—so each iteration overwrites the variable with the current object's keys instead of adding to it. That's why you end up with two separate arrays instead of one combined list.
Here are a few straightforward ways to fix this:
1. Initialize an empty array first, use concat() to merge
You need to create your result array outside the loop, then merge each set of keys into it on every iteration:
var body = { "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] }; // Simulating your request.body var keyes = []; // Initialize empty array outside the loop for(var i = 0; i < body.data.length; i++){ var obj = body.data[i]; keyes = keyes.concat(Object.keys(obj)); // Merge current keys into the result array } console.log(keyes); // Output: ['firstName', 'lastName']
2. Use push() with the spread operator (ES6+)
If you prefer mutating the array directly (which is slightly more efficient in some cases), you can use the spread operator to unpack the keys array and push each item into the result:
var body = { "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] }; var keyes = []; for(var i = 0; i < body.data.length; i++){ var obj = body.data[i]; keyes.push(...Object.keys(obj)); // Unpack keys and push to the array } console.log(keyes); // Output: ['firstName', 'lastName']
3. Clean ES6 one-liner with flatMap()
For a more concise approach, use flatMap()—it maps each object to its keys array, then flattens the result into a single array automatically:
var body = { "data": [ {"firstName": "Achmad"}, {"lastName": "a"} ] }; var keyes = body.data.flatMap(obj => Object.keys(obj)); console.log(keyes); // Output: ['firstName', 'lastName']
The core issue in your original code was that keyes was being redefined/overwritten in each loop iteration. By initializing the array outside the loop and accumulating the keys into it, you get the combined list you're looking for.
内容的提问来源于stack exchange,提问作者Ahmed

