Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 276
Callum Linington Avatar asked Jun 08 '16 15:06

Callum Linington


1 Answers

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);
like image 102
Pranav C Balan Avatar answered Oct 27 '22 01:10

Pranav C Balan