gpt4 book ai didi

javascript - 从数组列表更改为对象javascript

转载 作者:行者123 更新时间:2023-11-29 21:03:55 24 4
gpt4 key购买 nike

我的代码有问题,因为当我增加数组中的元素数量时,它只运行最后添加的 3 个元素,而不是完整列表 我不知道我的代码有什么问题。请帮忙!

var array = [
['make', 'Ford'],
['model', 'Mustang'],
['year', '1964'],
['make', 'Honda'],
['model', 'CRV'],
['year', '2000']
];

function fromListToObject(array) {
var obj = Object.create(null); // empty container for my object
for (var i = 0; i < array.length; i++) { //declare the 1st array loop
var arr1 = array[i]; //decleare the nested array
obj[arr1[0]] = arr1[1]; //1st item = 2nd item in the nested array
}
return obj;
}

var result = fromListToObject(array);
console.log(result);

最佳答案

您必须将数据放入一个对象数组中。我会将原始数组分块成当时键大小的 block ,然后处理这些 block 并为它们创建单独的对象。请注意,如果原始数组包含不相等的 block (例如缺少键),下面将失败,因此您需要为此添加检查或真正确保原始数组始终正确:

let array = [
['make', 'Ford'],
['model', 'Mustang'],
['year', '1964'],
['make', 'Honda'],
['model', 'CRV'],
['year', '2000']
];

function toArrOfObj(array) {
let keys = [...new Map(array).keys()];
let i, j, res = [], chunk = keys.length;
for (i = 0, j = array.length; i < j; i += chunk) {
let tmp = array.slice(i, i + chunk);
let obj = {};
for (let [k, v] of tmp) {
obj[k] = v;
}
res.push(obj);
}
return res;
}

console.log(toArrOfObj(array));

关于javascript - 从数组列表更改为对象javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45077849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com