Using array map to filter results with if conditional

前端 未结 3 2086
孤街浪徒
孤街浪徒 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:39

    You're looking for the .filter() function:

      $scope.appIds = $scope.applicationsHere.filter(function(obj) {
        return obj.selected;
      });
    

    That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

    edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

      $scope.appIds = $scope.applicationsHere.filter(function(obj) {
        return obj.selected;
      }).map(function(obj) { return obj.id; });
    

    Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

    0 讨论(0)
  • 2020-12-03 13:49

    Here's some info if someone comes upon this in 2019.

    I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

    One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

    Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

    Hope this helps someone

    0 讨论(0)
  • 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

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