I am trying to achieve the below:
var arr = [
{name: 'width', value: 10},
{name: 'height', value: 20},
]
arr.reduce((ack, item)=>{
ack.width = item.value
ack.height = item.value
return ack
},{})
//Expected output:
{width: 10, height: 20}
//Actual output:
{width: 20, height: 20}
Maybe I don’t understand how .reduce() works a 100%?
Advertisement
Answer
reduce method executes a callback function on each element of the array, so in your issue, on every iteration you have an object that contains name and value property. you can achieve your goal like this:
let arr = [
{name: 'width', value: 10},
{name: 'height', value: 20},
]
let result = arr.reduce((ack, item)=>{
ack[item.name] = item.value
return ack
},{})
console.log(result);