我现在被困了一整天,不能再进一步了。我知道,我错过了一件小事,但就是找不到。
我有两个数组:
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
}
任何想法都真的很受欢迎。
您可以使用模运算符来检查每个keys.length
第 n 个元素,然后通过切片开始是当前索引和结束当前索引 + keys.length 的值数组来添加一个新对象
const f = (keys, values) => values.reduce((r, e, i) => {
if (i % keys.length === 0) {
const index = i / keys.length
r[index] = values.slice(i, i + keys.length).reduce((r, e, i) => {
r[keys[i]] = e
return r
}, {})
}
return r
}, [])
console.log(f(["a", "b", "c"], [1, 2, 3, 4, 5, 6, 7, 8, 9]))
console.log(f(["a", "b", "c", 'g'], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
console.log(f(["a", "b"], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句