You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将嵌套数组转换为对象数组?

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.lenght instead of array.length (missing a t). This would cause your loop to behave unpredictably.
  • Incorrect loop boundary: Using i <= array.length will make your loop run one too many times (since array indices start at 0, the last valid index is array.length - 1). This would lead to trying to access array[i] when i equals the array length, which is undefined.
  • 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 res instead 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:25:59