Filtering array of objects based on value

前端 未结 3 846
孤街浪徒
孤街浪徒 2021-01-21 12:49

Is there a way to filter an array of objects by a particular value that could be in any property?

Let\'s say I have this object:

var x = [
    {
                 


        
相关标签:
3条回答
  • 2021-01-21 12:57

    Well the obvious thing is to combine your for..in loop with your .filter() function:

    var x = [{name: "one", swp: "two"}, {name: "two", swp: "three"}, { name: "aa", swp: "bb"}];
    
    var filtered = x.filter(function(v) {
      for (var k in v)
        if (v[k] === "two") return true;
    });
    console.log(filtered);

    0 讨论(0)
  • 2021-01-21 13:02

    use an inner loop method to check individual property values

    var val ="one";
    var res = x.filter(function(item){
         return Object.keys(item).some(function(prop){
             return item[prop] === val;
         });
    });
    
    0 讨论(0)
  • 2021-01-21 13:05
    var arrOfObj = []; // objects you're sifting
    var prop = 'whatever';
    
    var matches = arrOfObj.filter(obj => Object.keys(obj).some(k => obj[k] === prop));
    

    You want a combination of Array.prototype.filter and Array.prototype.some which returns a boolean if any of the elements of the array match the condition, it also stops iterating the array (in this case the keys of each object) as soon as it finds a match. If you need cross-browser support (and for some reason aren't using babel) the ES 5 version of the above is

    var arrOfObj = []; // objects you're sifting
    var prop = 'whatever';
    
    var matches = arrOfObj.filter(function(obj) { 
      return Object.keys(obj).some(function(k) { 
        return obj[k] === prop; 
      });
    });
    
    0 讨论(0)
提交回复
热议问题