Nishanth Matha Nishanth Matha - 11 months ago 68
JSON Question

E6 arrow functions reduce an array of object to single object

I've an array like:


I'm trying to reduce this array to one object

Expected output


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


As simple as

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