1

[1,2].reduce((accum,val) => ({val}) ,{})

I expect above reduce function will return {1:1, 2:2} but it didn't, what's wrong? isn't I've return an object?

4 Answers 4

5

You need to spread the accumulator (working with newer JS or with babeljs) and computed property names.

console.log([1, 2].reduce((accum, val) => ({ ...accum, [val]: val }), {}));

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

Comments

0
[1,2].reduce((accum,val) => { accum[val] = val
return accum } ,{})

This will do the trick. You weren't referencing the starting object.

Comments

0

One option is using Object.assign to add new property and values

var result = [1, 2].reduce((accum, val) => Object.assign(accum, {[val]: val}), {})
console.log(result);

Doc: Object.assign

Comments

0

Use can write like this: You need to spread accumulator value.

[1,2].reduce((accum,val) => ({...accum, [val]:val}) ,{})

Comments

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.