Using array map to filter results with if conditional

前端 未结 3 2095
孤街浪徒
孤街浪徒 2020-12-03 13:01

I am trying to use an array map to filter a object a bit further to prepare it to send to the server to for saving. I can filter to 1 key value, which is great, but I want t

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 13:57

    You should use Array.prototype.reduce to do this. I did do a little JS perf test to verify that this is more performant than doing a .filter + .map.

    $scope.appIds = $scope.applicationsHere.reduce(function(ids, obj){
        if(obj.selected === true){
            ids.push(obj.id);
        }
        return ids;
    }, []);
    

    Just for the sake of clarity, here's the sample .reduce I used in the JSPerf test:

      var things = [
        {id: 1, selected: true},
        {id: 2, selected: true},
        {id: 3, selected: true},
        {id: 4, selected: true},
        {id: 5, selected: false},
        {id: 6, selected: true},
        {id: 7, selected: false},
        {id: 8, selected: true},
        {id: 9, selected: false},
        {id: 10, selected: true},
      ];
      
      	
    var ids = things.reduce((ids, thing) => {
      if (thing.selected) {
        ids.push(thing.id);
      }
      return ids;
    }, []);
    
    console.log(ids)


    EDIT 1

    Note, As of 2/2018 Reduce + Push is fastest in Chrome and Edge, but slower than Filter + Map in Firefox

提交回复
热议问题