alexmac
alexmac

Reputation: 19617

Simplest way to create a new object based on the original, but without a few fields

I need to create a new object based on the original with all the fields, but without some of them. In my current implementation I enumerate all the fields, and exclude don't needed:

var obj1 = {
  a: 1,
  b: 2,
  c: 3
};

var keys = _.keys(obj);
_.remove(keys, 'c');

var obj2 = _.pick(obj1, keys);
console.log(obj2); // => { a: 1, b: 2 }

But I don't like that, can somebody suggest more easiest way? For example in mongoose, find method accepts a string of fields, separated by comma, and to exclude any field, I need to add minus symbol only: name email -password.

Upvotes: 0

Views: 69

Answers (3)

Brian Pursley
Brian Pursley

Reputation: 1196

If you are using underscorejs it is pretty simple, just use ._omit()

var obj1 = {
  a: 1,
  b: 2,
  c: 3
};

var obj2 = _.omit(obj1, ["c"]);

jsfiddle: https://jsfiddle.net/bpursley/hnh5ecam/

Upvotes: 1

unscsprt
unscsprt

Reputation: 1

You could create a function that does this, and you don't need to rely on underscore.

function partialClone(obj, excluded) {
  var clone = {};

  for (var key in obj) {
    if (!excluded.includes(key)) {
      clone[key] = obj[key];
    }
  }

  return clone;
}

Working jsFiddle

Upvotes: 0

Mark
Mark

Reputation: 569

You could try something like this:

var obj2 = {},
    forbiddenProperties = ['c', 'd'];

Object.keys(obj1).forEach(function (key) {
   if (forbiddenProperties.indexOf(key) >= 0) {
      obj2[key] = obj1[key];
   }
});

Upvotes: 0

Related Questions