I am trying to achieve the below:
JavaScript
x
19
19
1
var arr = [
2
{name: 'width', value: 10},
3
{name: 'height', value: 20},
4
]
5
6
arr.reduce((ack, item)=>{
7
ack.width = item.value
8
ack.height = item.value
9
return ack
10
},{})
11
12
//Expected output:
13
14
{width: 10, height: 20}
15
16
//Actual output:
17
18
{width: 20, height: 20}
19
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:
JavaScript
1
11
11
1
let arr = [
2
{name: 'width', value: 10},
3
{name: 'height', value: 20},
4
]
5
6
let result = arr.reduce((ack, item)=>{
7
ack[item.name] = item.value
8
return ack
9
},{})
10
11
console.log(result);