[removed] filter() for Objects

前端 未结 16 794
心在旅途
心在旅途 2020-11-22 15:23

ECMAScript 5 has the filter() prototype for Array types, but not Object types, if I understand correctly.

How would I implemen

相关标签:
16条回答
  • 2020-11-22 15:46

    In these cases I use the jquery $.map, which can handle objects. As mentioned on other answers, it's not a good practice to change native prototypes (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#Bad_practice_Extension_of_native_prototypes)

    Below is an example of filtering just by checking some property of your object. It returns the own object if your condition is true or returns undefined if not. The undefined property will make that record disappear from your object list;

    $.map(yourObject, (el, index)=>{
        return el.yourProperty ? el : undefined;
    });
    
    0 讨论(0)
  • 2020-11-22 15:50

    Solution in Vanilla JS from year 2020.


    let romNumbers={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
    

    You can filter romNumbers object by key:

    const filteredByKey = Object.fromEntries(Object.entries(romNumbers).filter(([key, value]) => key === 'I'))
    // filteredByKey = {I: 1} 
    

    Or filter romNumbers object by value:

     const filteredByValue = Object.fromEntries(Object.entries(romNumbers).filter(([key, value]) => value === 5))
     // filteredByValue = {V: 5} 
    
    0 讨论(0)
  • 2020-11-22 15:52

    I use this when I need it:

    const filterObject = (obj, condition) => {
        const filteredObj = {};
        Object.keys(obj).map(key => {
          if (condition(key)) {
            dataFiltered[key] = obj[key];
          }
        });
      return filteredObj;
    }
    
    0 讨论(0)
  • 2020-11-22 15:53

    I have created an Object.filter() which does not only filter by a function, but also accepts an array of keys to include. The optional third parameter will allow you to invert the filter.

    Given:

    var foo = {
        x: 1,
        y: 0,
        z: -1,
        a: 'Hello',
        b: 'World'
    }
    

    Array:

    Object.filter(foo, ['z', 'a', 'b'], true);
    

    Function:

    Object.filter(foo, function (key, value) {
        return Ext.isString(value);
    });
    

    Code

    Disclaimer: I chose to use Ext JS core for brevity. Did not feel it was necessary to write type checkers for object types as it was not part of the question.

    // Helper function
    function print(obj) {
        document.getElementById('disp').innerHTML += JSON.stringify(obj, undefined, '  ') + '<br />';
        console.log(obj);
    }
    
    Object.filter = function (obj, ignore, invert) {
        let result = {}; // Returns a filtered copy of the original list
        if (ignore === undefined) {
            return obj;   
        }
        invert = invert || false;
        let not = function(condition, yes) { return yes ? !condition : condition; };
        let isArray = Ext.isArray(ignore);
        for (var key in obj) {
            if (obj.hasOwnProperty(key) &&
                    !(isArray && not(!Ext.Array.contains(ignore, key), invert)) &&
                    !(!isArray && not(!ignore.call(undefined, key, obj[key]), invert))) {
                result[key] = obj[key];
            }
        }
        return result;
    };
    
    let foo = {
        x: 1,
        y: 0,
        z: -1,
        a: 'Hello',
        b: 'World'
    };
    
    print(Object.filter(foo, ['z', 'a', 'b'], true));
    print(Object.filter(foo, (key, value) => Ext.isString(value)));
    #disp {
        white-space: pre;
        font-family: monospace
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/extjs/4.2.1/builds/ext-core.min.js"></script>
    <div id="disp"></div>

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