How to omit specific properties from an object in JavaScript

后端 未结 14 1253
无人共我
无人共我 2021-02-01 14:50

Is there a clean way to return a new object that omits certain properties that the original object contains without having to use something like lodash?

相关标签:
14条回答
  • 2021-02-01 15:42

    var obj = {
      a: 1,
      b: 2,
      c: 3,
      d: {
        c: 3,
        e: 5
      }
    };
    
    Object.extract = function(obj, keys, exclude) {
      var clone = Object.assign({}, obj);
      if (keys && (keys instanceof Array)) {
        for (var k in clone) {
          var hasKey = keys.indexOf(k) >= 0;
          if ((!hasKey && !exclude) || (hasKey && exclude)) {
            delete clone[k];
          }
        }
      }
      return clone;
    };
    
    console.log('Extract specified keys: \n-----------------------');
    var clone1 = Object.extract(obj, ['a', 'd']);
    console.log(clone1);
    console.log('Exclude specified keys: \n-----------------------');
    var clone2 = Object.extract(obj, ['a', 'd'], true);
    console.log(clone2);

    0 讨论(0)
  • 2021-02-01 15:46
    function omitKeys(obj, keys) {
            var target = {}; 
    
            for (var i in obj) { 
                if (keys.indexOf(i) >= 0) continue;
                if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; 
    
                target[i] = obj[i]; 
            } 
    
            return target; 
        }
    
    0 讨论(0)
提交回复
热议问题