Callum Linington Callum Linington - 6 months ago 13
Javascript Question

JavaScript Reduce Array of objects to object dictionary

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!

Answer

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);