Keeping only certain properties in a JavaScript object

后端 未结 11 1022
时光说笑
时光说笑 2020-12-20 11:05

I have an object. I would like to modify the object (not clone it) by removing all properties except for certain specific properties. For instance, if I started with this o

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 11:55

    I suppose you could add a new method to the prototype:

    if (!('keepOnlyTheseProps' in Object.prototype)) {
      Object.prototype.keepOnlyTheseProps = function (arr) {
        var keys = Object.keys(this);
        for (var i = 0, l = keys.length; i < l; i++) {
          if (arr.indexOf(keys[i]) < 0) delete this[keys[i]];
        }
      }
    }
    
    myObj.keepOnlyTheseProps(['p1', 'p2', 'p100']);
    

    Fiddle.

提交回复
热议问题