2

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}.

I'm getting:

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

at Array.reduce

What am I doing wrong?

4
  • 1
    Object.fromEntries(keys.map((val,i)=>[val,vals[i]])) Commented Jun 21, 2020 at 13:13
  • You need to return the accumulator itself. Commented Jun 21, 2020 at 13:13
  • 1
    return acc[key]=vals[i]; - Replace return with console.log() and check the output Commented Jun 21, 2020 at 13:13
  • the accumulator is getting corrupted because you are not returning the accumulator at the end Commented Jun 21, 2020 at 13:25

3 Answers 3

4

If you want to use reduce method then its fine, but you will have to return the accumulator to make it work.

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

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

Sign up to request clarification or add additional context in comments.

Comments

2

You need to return object as acc. 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);

2 Comments

changed the return statement
Thank you very much!
1

return acc[key]=vals[i]; actually return the value of vals[i] ==> you finally get h only on https://playcode.io/ environment.

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")
  • 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

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

2 Comments

Thanks Tony , I'm learning a lot from this. Very cool!
I am glad it helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.