JavaScript Reduce Array of objects to object dictionary

后端 未结 1 749
独厮守ぢ
独厮守ぢ 2021-01-05 05:38

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         


        
相关标签:
1条回答
  • 2021-01-05 06:13

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

    0 讨论(0)
提交回复
热议问题