[removed] filter() for Objects

前端 未结 16 975
心在旅途
心在旅途 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: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, '  ') + '
    '; 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
    }
    
    

提交回复
热议问题