Monday, May 20, 2024
132
rated 0 times [  134] [ 2]  / answers: 1 / hits: 23059  / 8 Years ago, wed, june 8, 2016, 12:00:00

I've read this answer on SO to try and understand where I'm going wrong, but not quite getting there.



I have this function :



get() {
var result = {};

this.filters.forEach(filter => result[filter.name] = filter.value);

return result;
}


It turns this :



[
{ name: Some, value: 20160608 }
]


To this :



{ Some: 20160608 }


And I thought, that is exactly what reduce is for, I have an array, and I want one single value at the end of it.



So I thought this :



this.filters.reduce((result, filter) => {
result[filter.name] = filter.value;
return result;
});


But that doesn't produce the correct result.




1) Can I use Reduce here?



2) Why does it not produce the correct result.




From my understanding, the first iteration the result would be an empty object of some description, but it is the array itself.



So how would you go about redefining that on the first iteration - these thoughts provoke the feeling that it isn't right in this situation!


More From » ecmascript-6

 Answers
33

Set initial value as object



this.filters = this.filters.reduce((result, filter) => {
result[filter.name] = filter.value;
return result;
},{});
//-^----------- here




var filters = [{
name: Some,
value: 20160608
}];

filters = filters.reduce((result, filter) => {
result[filter.name] = filter.value;
return result;
}, {});

console.log(filters);







var filters = [{
name: Some,
value: 20160608
}];

filters = filters.reduce((result, {name, value}= filter) => (result[name] = value, result), {});

console.log(filters);




[#61846] Tuesday, June 7, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
meadowe

Total Points: 0
Total Questions: 97
Total Answers: 97

Location: Laos
Member since Fri, Sep 11, 2020
4 Years ago
;