11

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!

Community
  • 1
  • 1
Callum Linington
  • 14,213
  • 12
  • 75
  • 154

2 Answers2

34

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
2

Since 2019 (ES2019) you can go with Object.fromEntries() but you need to map to array first.

const filtersObject = Object.fromEntries(filters.map(({ name, value }) => [name, value])
Ondra
  • 943
  • 12
  • 19