gpt4 book ai didi

从数组合并到对象后的Javascript

转载 作者:行者123 更新时间:2023-12-01 00:43:18 25 4
gpt4 key购买 nike

const arrays = [
[123, "string1"],
[4564564, "string2"],
[392341231, "string3"],
[1665342, "String4", 334934543, "string5"]
];

const s = arrays.reduce((acc, val) => {
return acc.concat(val);
});

// output:
// [123, "string1", 4564564, "string2", 392341231, "string3", 1665342, "String4", 334934543, "string5"]

压平数组后,输出是一个数字一个字符串,我试图使用reduce来制作一个像

{
123: "string1",
4564564: "string2",
392341231: "string3",
1665342: "String4",
334934543: "string5"
}
.reduce(function(acc, cur, i) {
acc[cur] = cur;
return acc;
}, {});

输出错误,如何在reduce中分离numberstring?谢谢

最佳答案

您需要保留键和值。迭代每个子数组,将第二项(值)分配到第一项(键)处的累加器上:

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);

关于从数组合并到对象后的Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57564895/

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