Nishanth Matha
Nishanth Matha

Reputation: 6081

E6 arrow functions reduce an array of object to single object

I've an array like:

a=[{'test':1,'test2':'2'},{'test':3,'test2':'4'}]

I'm trying to reduce this array to one object

Expected output

{1:2,3:4}

I've tried:

let newObj = a.reduce((pre,curr)=>Object.assign({},{curr.test:curr.test2}))//unexpected token at .
let newObj = a.reduce((pre,curr)=>Object.assign({},{curr['test']:curr['test2']}))//unexpected token at [

P.S: I have already achieved what I'm trying by not using arrow functions, I want to know why the above methods doesn't work

Upvotes: 0

Views: 128

Answers (1)

zerkms
zerkms

Reputation: 255015

As simple as

a.reduce(
    (acc, {test: key, test2: value}) => Object.assign({}, acc, {[key]: value}),
    {}
)

So what you're doing here is - destructure the every element to key and value, then combine the current accumulator with the new object that consists of just those key-value pair.

What you were doing wrong: you cannot use expressions as object keys as-is, but you must wrap those in the square brackets.

So this {[curr.test]: curr.test2} would work.

Upvotes: 3

Related Questions