3 回答
TA贡献1798条经验 获得超7个赞
您可以通过映射各个索引并将它们全部分配给一个新对象来轻松完成,这将减少您对中间步骤的需求
const arrays = [
[123, "string1"],
[4564564, "string2"],
[392341231, "string3"],
[1665342, "String4", 334934543, "string5"]
];
console.log( Object.assign( {}, ...arrays.map( i => ({[i[0]]: i[1] }) ) ) );
TA贡献1815条经验 获得超6个赞
你必须保持两个键和值。迭代每个子数组,将第二项(值)分配到第一项(键)处的累加器:
const arrays = [
[123, "string1"],
[4564564, "string2"],
[392341231, "string3"],
[1665342, "String4", 334934543, "string5"]
];
const obj = arrays.reduce((a, subarr) => {
for (let i = 0; i < subarr.length; i += 2) {
a[subarr[i]] = subarr[i + 1];
}
return a;
}, {});
console.log(obj);
TA贡献1875条经验 获得超3个赞
你可以这样做:
const arrays = [
[123, "string1"],
[4564564, "string2"],
[392341231, "string3"],
[1665342, "String4", 334934543, "string5"]
];
const s = arrays.reduce((acc, val) => {
let i = 0
while (i < val.length) {
acc[val[i]] = val[i + 1];
i += 2
}
return acc;
},{});
console.log( s )
添加回答
举报