What is the best way in JavaScript to trim down the properties of an object?

- 1 answer

Ad

Situation:

I have an object like

{ prop_1 : val_1, prop_2 : val_2, prop_3 : val_3 , ..., prop_N : val_N } 

and I want to remove all properties that aren't prop_i, prop_j or prop_K ?

What is the best way to do this other than the "brute force" way of

var original = { prop_1 : val_1, prop_2 : val_2, prop_3 : val_3 , ..., prop_N : val_N };
var newguy = { prop_i : original.prop_i, prop_j : original.prop_j, prop_k : original.prop_k };
original = newguy;

????

Ad

Answer

Ad

Well you can do a function to help you do that.

(function() {
  'use strict';

  function copyOnly(obj, keysToPreserve) {
    var result = {};
    for (var i = 0, length = keysToPreserve.length; i < length; ++i) {
      var key = keysToPreserve[i];
      result[key] = obj[key];
    }
    return result;
  }

  function copyExclude(obj, keysToExclude) {
    var result = {};
    for (var key in obj) {
      if (obj.hasOwnProperty(key) && keysToExclude.indexOf(key) === -1) { // -1 means key doesn't exist in keysToExclude
        result[key] = obj[key];
      }
    }
    return result;
  }

  var original = {
    a: '1',
    b: '2',
    c: '3',
    d: '4',
    e: '5'
  };

  var toPreserve = ['a', 'b', 'c'];
  var result1 = copyOnly(original, toPreserve);
  
  var toExclude = ['d', 'e'];
  var result2 = copyExclude(original, toExclude);
  
  // result1 will have the same structure as result2
  
  document.getElementById('result').innerHTML = 'result1 = ' + JSON.stringify(result1) + '\n' + 'result2 = ' + JSON.stringify(result2);
})();
<pre id="result"></pre>

Ad
source: stackoverflow.com
Ad