gpt4 book ai didi

javascript - 如何从两个非对称数组中创建一个对象数组?

转载 作者:行者123 更新时间:2023-12-05 08:45:29 26 4
gpt4 key购买 nike

我现在被困了一整天,无法继续前进。我知道,我错过了一件小事,但就是找不到。

我有两个数组:

arrKeys = ["a", "b", "c"]
arrValues = [ 1, 2, 3, 4, 5, 6, 7, 8, 9]

我想得到一个对象数组,它看起来像:

myObj = [
{
"a": 1,
"b": 2,
"c": 3
},
{
"a": 4,
"b": 5,
"c": 6
},
{
"a": 7,
"b": 8,
"c": 9
}
]

我尝试做类似的事情:

const myObj = arrKeys.reduce((newObj, key, index) => {
if (arrValues[index] == undefined) arrValues[index] = null
newObj[key] = aarValues[index]
return newObj
}, {})
cosnole.log(myObj)

但问题是,arrKeys 只循环一次,我不知道如何在每次 arrKeys 达到最大长度时“重置”计数器。我也只得到一个对象,而不是对象数组:

我的结果

myObj = {
"a": 1,
"b": 2,
"c": 3
}

非常感谢任何想法。

最佳答案

您可以迭代这些值,一次创建 arrKeys.length block ,然后通过将 block 索引映射到适当的键来从该 block 创建一个对象。这种方法的优点是如果 arrValues 不是 arrKeys 长度的精确倍数,它仍然有效:

const f = (arrKeys, arrValues) => {
const result = []
const kLen = arrKeys.length
const vLen = arrValues.length
for (i = 0; i < vLen; i += kLen) {
chunk = arrValues.slice(i, i + kLen)
result.push(Object.fromEntries(chunk.map((v, i) => [arrKeys[i], v])))
}
return result;
}

console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))
console.log(f(["a", "b", "c", "d"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))

关于javascript - 如何从两个非对称数组中创建一个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72610318/

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