简体   繁体   English

JS reduce: TypeError: Cannot create property at Array.reduce

[英]JS reduce: TypeError: Cannot create property at Array.reduce

I have the following:我有以下内容:

let keys = ['a','b','c'];
let vals = ['1','b','h'];
const my_obj = keys.reduce(function(acc,key,i) {
return acc[key]=vals[i];
},{});

logger.log(my_obj);

I would like my_obj to be {a:1,b:b,c:h} .我希望my_obj{a:1,b:b,c:h}

I'm getting:我越来越:

TypeError: Cannot create property 'b' on string '1'

at Array.reduce

What am I doing wrong?我究竟做错了什么?

If you want to use reduce method then its fine, but you will have to return the accumulator to make it work.如果你想使用 reduce 方法,那很好,但你必须返回累加器才能使其工作。

 let keys = ['a', 'b', 'c']; let vals = ['1', 'b', 'h']; const my_obj = keys.reduce(function(acc, key, i) { acc[key] = vals[i]; return acc; }, {}); console.log(my_obj);

But I will suggest to use the simple for loop, because of just the simplicity of problem但我会建议使用简单的 for 循环,因为问题很简单

 let keys = ['a', 'b', 'c']; let vals = ['1', 'b', 'h']; let my_obj = {}; for (let i = 0; i < keys.length; i++) my_obj[keys[i]] = vals[i]; console.log(my_obj);

You need to return object as acc.您需要按照要求返回 object。 In your code you are returning the assigned value在您的代码中,您将返回分配的值

 let keys = ['a', 'b', 'c']; let vals = ['1', 'b', 'h']; const my_obj = keys.reduce(function(acc, key, i) { acc[key] = vals[i]; return acc; }, {}); console.log(my_obj);

return acc[key]=vals[i]; actually return the value of vals[i] ==> you finally get h only on https://playcode.io/ environment.实际上返回vals[i] ==> 你最终只能在https://playcode.io/环境中获得h的值。

Updated: in your environment, you got that error because:更新:在您的环境中,您收到该错误是因为:

  • after first run of keys.reduce your next acc will be "1" (return acc[key]= vals[0]} equal return vals[0] which is "1" )在第一次运行keys.reduce之后,您的下一个acc将是"1" (返回acc[key]= vals[0]}等于返回vals[0] ,即"1"
  • Now you come to second round of keys.reduce , your acc is "1" then you set acc[key]= vals[1]} equal "1"[b] = vals[1] ==> you got that error现在你来到第二轮keys.reduce ,你的 acc 是"1"然后你设置acc[key]= vals[1]}等于"1"[b] = vals[1] ==> 你得到那个错误

Try this:尝试这个:

 let keys = ['a','b','c']; let vals = ['1','b','h']; const my_obj = keys.reduce(function(acc,key,i) { // return new expanded acc return ({...acc, [key]: vals[i]}) },{}); console.log(my_obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM