如何将嵌套数组转换为对象数组?
Fixing Your Nested Array to Object Array Conversion
Hey there! Let's get your array conversion working properly. I've looked at your code and spotted a few small issues that are keeping it from working as expected—let's break them down and fix them step by step.
First, let's go over the problems in your original code:
- Spelling mistake: You wrote
array.lenghtinstead ofarray.length(missing at). This would cause your loop to behave unpredictably. - Incorrect loop boundary: Using
i <= array.lengthwill make your loop run one too many times (since array indices start at 0, the last valid index isarray.length - 1). This would lead to trying to accessarray[i]wheniequals the array length, which isundefined. - Resetting the result array: You declare
var res = []inside the loop, which means it gets emptied every time the loop runs. By the end, you'd only have the last element in the array. - Not creating the target object: You're pushing the original sub-array into
resinstead of converting it to the{id: ..., score: ...}format you need.
Here's the fixed version using a for loop:
const array = [[1, 698],[32, 798],[69, 830],[95, 500]]; const res = []; // Declare the result array once, outside the loop for(let i = 0; i < array.length; i++){ // Fixed spelling and loop condition const obj = { id: array[i][0], // Grab the first element of the sub-array as id score: array[i][1] // Grab the second element as score }; res.push(obj); // Add the new object to the result array } console.log(res); // Output: [{id:1, score:698}, {id:32, score:798}, {id:69, score:830}, {id:95, score:500}]
Even better: Use Array.map() for a cleaner solution
Since you're transforming every element of the array into a new format, JavaScript's map() method is perfect for this—it's designed exactly for this kind of array-to-array transformation, and it's more concise:
const array = [[1, 698],[32, 798],[69, 830],[95, 500]]; const res = array.map(item => ({ id: item[0], score: item[1] })); console.log(res); // Same desired output as above
map() iterates over each element in the original array, runs your callback function on it, and collects all the returned values into a new array—no need to manually manage a loop counter or push to a result array.
内容的提问来源于stack exchange,提问作者arkahn jihu
相关产品推荐
相关产品推荐

