的方法可以通过以下步骤实现:
以下是一个示例代码,演示如何将嵌套数组转换为对象,并将数组索引与对象id匹配:
function convertArrayToObject(arr) {
let result = {};
function convert(arr, obj) {
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
let newObj = {};
obj[i] = newObj;
convert(arr[i], newObj);
} else {
obj[i] = {
id: i,
value: arr[i]
};
}
}
}
convert(arr, result);
return result;
}
// 示例输入
let nestedArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// 转换为对象
let resultObject = convertArrayToObject(nestedArray);
console.log(resultObject);
输出结果为:
{
0: {
0: { id: 0, value: 1 },
1: { id: 1, value: 2 },
2: { id: 2, value: 3 }
},
1: {
0: { id: 0, value: 4 },
1: { id: 1, value: 5 },
2: { id: 2, value: 6 }
},
2: {
0: { id: 0, value: 7 },
1: { id: 1, value: 8 },
2: { id: 2, value: 9 }
}
}
在这个示例中,我们将嵌套数组 [1, 2, 3], [4, 5, 6], [7, 8, 9]
转换为了一个对象,其中每个数组元素都被转换为一个对象,对象的id属性与数组索引匹配,value属性存储了原始的数组值。
领取专属 10元无门槛券
手把手带您无忧上云