44

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?

Mosh Feu
  • 24,625
  • 12
  • 74
  • 111
Aweb
  • 441
  • 1
  • 4
  • 6
  • Code? I would suggest create a new anonymous type, passing in what you want to keep – Edward Mar 25 '17 at 02:12
  • A similar question was asked here http://stackoverflow.com/questions/34698905/clone-a-js-object-except-for-one-key – gabesoft Mar 25 '17 at 02:22
  • 4
    Possible duplicate of [clone a js object except for one key](http://stackoverflow.com/questions/34698905/clone-a-js-object-except-for-one-key) – gyre Mar 25 '17 at 02:41
  • Possible duplicate of [How do I remove a property from a JavaScript object?](https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object) – NIKHIL C M Jun 19 '19 at 07:33

15 Answers15

82
const { bar, baz, ...qux } = foo

Now your object qux has all of the properties of foo except for bar and baz.

Miroslav Glamuzina
  • 4,201
  • 2
  • 15
  • 30
Craig Gehring
  • 1,509
  • 6
  • 10
  • 1
    Keep in mind, this will not clone the object. Updating any values ion `qux` will update the values in `foo`. Javascript objects are passed by reference. – Miroslav Glamuzina Mar 12 '19 at 01:17
  • 11
    @MiroslavGlamuzina that's not correct. If you change a value in `qux` then `foo`'s value will not be updated. However, if the value of a property of `qux` is an object and you change something in that object, then the object referenced by the corresponding property of `foo` would also be changed. – Steven Oxley Jan 29 '20 at 05:51
  • Just a small note, in chrome (as of version 87.0.4280.141), this doesn't work with quoted property names. I don't know about other environments: `const { "bar", 'baz', ...qux } = foo` – Sledge Feb 04 '21 at 03:23
31

If you know the list of the properties that you want preserved as well as omitted, the following "whitelisting" approach should work:

const exampleFilter = ({ keepMe, keepMeToo }) => ({ keepMe, keepMeToo })

console.log(
  exampleFilter({
    keepMe: 'keepMe',
    keepMeToo: 'keepMeToo',
    omitMe: 'omitMe',
    omitMeToo: 'omitMeToo'
  })
)
gyre
  • 14,437
  • 1
  • 32
  • 46
  • This has blown my mind, could you explain how it works? – rorymorris89 Mar 25 '17 at 02:25
  • It uses a combination of [parameter destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and default object values (each key is mapped to the value held by the variable of the same name, e.g. `{ keepMe, keepMeToo }` is like `{ keepMe: keepMe, keepMeToo: keepMeToo }`. – gyre Mar 25 '17 at 02:30
  • 1
    Thanks! Cracking answer and upvoted for awesomeness. – rorymorris89 Mar 25 '17 at 02:37
  • Wow! Thank you for this! I was struggling with finding an answer, and then this came up! This solved my problem beautifully – J.H Sep 04 '20 at 22:45
  • Great anwser! Wonder if there is a way to avoid duplicating field names, couldn't find any. – Camilo Jan 30 '21 at 22:52
22

In modern environments you can use this code snippet:

function omit(key, obj) {
  const { [key]: omitted, ...rest } = obj;
  return rest;
}
Eddie Cooro
  • 1,029
  • 11
  • 17
  • 2
    "modern environments" meaning if you're shipping un-transpiled code, this will work on 93% of browsers. See full compatibility at https://caniuse.com/mdn-javascript_operators_spread_spread_in_destructuring – Dawson B Feb 04 '21 at 19:18
20
const {omittedPropertyA, omittedPropertyB, ...remainingObject} = originalObject;

Explanation:

With ES7

you could use object destructuring and the spread operator to omit properties from a javascript object:

const animalObject = { 'bear': 1, 'snake': '2', 'cow': 3 };
 
const {bear, ...other} = animalObject

// other is: { 'snake': '2', 'cow:'  3}

source: https://remotedevdaily.com/two-ways-to-omit-properties-from-a-javascript-object/

Community
  • 1
  • 1
Geoffrey Hale
  • 8,152
  • 4
  • 34
  • 42
  • I find this solution super helpful, but I’m working with a large object ( about 200 key pairs ) and I want to create a new object that has only the values I specify ( about 30 ) , not the values I don’t want ( which would be about 160 ). Even 30 values seems like a lot so I wonder if I can pass in an array? – ETHan Jul 18 '20 at 04:14
  • can i use a variable instead of bear inside `const {bear, ...other} =` – SamuraiJack Sep 07 '20 at 17:28
  • @SamuraiJack yes you can. `const fieldName = 'bear'; const {[fieldName]: _, ...other} = animalObject` – brianbhsu Jan 14 '21 at 20:31
12

There's the blacklist package on npm which has a very flexible api.

Also a situational trick using the object rest-spread proposal (stage-3).

const {a, b, ...rest} = {a: 1, b: 2, c: 3, d: 4};
a // 1
b // 2
rest // {c: 3, d: 4}

This is often used in react components where you want to use a few properties and pass the rest as props to a <div {...props} /> or similar.

Brigand
  • 75,952
  • 19
  • 155
  • 166
10

const x = {obj1: 1, obj2: 3, obj3:26};


const {obj1,obj2, ...rest} = x;
console.log(rest)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>
  • Note that if you use a linter such as eslint, it could flag unused variables as errors with this approach. – Kev Apr 28 '21 at 10:45
7

Omit and array of keys, using ES7 w/ recursion.

function omit(keys, obj) {
  if (!keys.length) return obj
  const { [keys.pop()]: omitted, ...rest } = obj;
  return omit(keys, rest);
}

This builds on top of @Eddie Cooro answer.

will Farrell
  • 1,549
  • 1
  • 15
  • 19
  • 3
    non-recursive version: ` function omit(keys, obj) { return keys.reduce((a, e) => { const { [e]: omit, ...rest } = a; return rest; }, obj) } ` – Magical Gordon Aug 05 '20 at 19:33
2

You can use Object.assign(), delete

var not = ["a", "b"]; // properties to delete from obj object
var o = Object.assign({}, obj);
for (let n of not) delete o[n];

Alternatively

var props = ["c", "d"];
let o = Object.assign({}, ...props.map(prop => ({[prop]:obj[prop]})));
guest271314
  • 1
  • 10
  • 82
  • 156
2

Sure, why not something like:

var original = {
  name: 'Rory',
  state: 'Bored',
  age: '27'
};

var copied = Object.assign({}, original);
delete copied.age;

console.log(copied);

https://jsfiddle.net/4nL08zk4/

rorymorris89
  • 1,044
  • 6
  • 14
1
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; 
    }
Andrés Andrade
  • 2,017
  • 2
  • 14
  • 20
1

A solution that hasn't been mentioned yet:

Omit single

o = {a: 5, b: 6, c: 7}
Object.fromEntries(Object.entries(o).filter(e => e[0] != 'b'))
// Object { a: 5, c: 7 }

Omit multiple

o = {a: 1, b: 2, c: 3, d: 4}
exclude = new Set(['a', 'b'])
Object.fromEntries(Object.entries(o).filter(e => !exclude.has(e[0])))
// Object { c: 3, d: 4 }

The Set above is used because it leads to linearithmic complexity even if the number of elements in exclude is in the same asymptotic equivalence class as the number of elements in o.

Grant Zvolsky
  • 41
  • 1
  • 4
  • Good one! **Hint:** You don't necessarily have to create a set using `exclude = ['a', 'b']` and `Object.fromEntries(Object.entries(o).filter(e => !exclude.includes(e[0])))` would suffice (besides the confusing `exclude.includes` of curse :D). – shaedrich Apr 13 '21 at 13:39
  • You're right. Didn't think of that. Sound be more performant. – shaedrich Apr 13 '21 at 15:54
0

One solution, I'm sure many others exist.

const testObj = {
    prop1: 'value1',
    prop2: 'value2',
    prop3: 'value3'
};

const removeProps = (...propsToFilter) => obj => {
   return Object.keys(obj)
   .filter(key => !propsToFilter.includes(key))
   .reduce((newObj, key) => {
       newObj[key] = obj[key];
       return newObj;
   }, {});
};


console.log(removeProps('prop3')(testObj));
console.log(removeProps('prop1', 'prop2')(testObj));

Edit: I always forget about delete...

const testObj = {
    prop1: 'value1',
    prop2: 'value2',
    prop3: 'value3'
};

const removeProps = (...propsToFilter) => obj => {
   const newObj = Object.assign({}, obj);
   propsToFilter.forEach(key => delete newObj[key]);
   return newObj;
};


console.log(removeProps('prop3')(testObj));
console.log(removeProps('prop1', 'prop2')(testObj));
Alex Young
  • 3,828
  • 1
  • 14
  • 33
0

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);
ajai Jothi
  • 2,131
  • 1
  • 6
  • 15
0

If you already use lodash, you may also do omit(obj, ["properties", "to", "omit"]) to get a new Object without the properties provided in the array.

Mitsakos
  • 134
  • 1
  • 3
  • 8
0

I saw this question and I wanted to remove 1 specific key, not a full method, so here's my suggestion:

const originalObj = {wantedKey: 111, anotherWantedKey: 222, unwantedKey: 1010};
const cleanedObj = Object.assign(originalObj, {unwantedKey: undefined});
Leyb
  • 3
  • 4
  • It does not work this way: if you have the value in the source - it overwrites the corresponding value in the target. In the given case, unwantedKey will be copied and be 1010. – Alexander Dec 01 '20 at 14:52