How to omit specific properties from an object in JavaScript

JavascriptEcmascript 6

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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

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

Solution 2 - Javascript

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'
  })
)

Solution 3 - Javascript

In modern environments you can use this code snippet:

function omit(key, obj) {
  const { [key]: omitted, ...rest } = obj;
  return rest;
}

Solution 4 - Javascript

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/

Solution 5 - Javascript

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.

Solution 6 - Javascript

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>

Solution 7 - Javascript

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.

Solution 8 - Javascript

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.

Solution 9 - Javascript

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]})));

Solution 10 - Javascript

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/

Solution 11 - Javascript

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.

Solution 12 - Javascript

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; 
	}

Solution 13 - Javascript

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);

Solution 14 - Javascript

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));

Solution 15 - Javascript

Omit multiple keys from the object (immutable)

export const omit = (obj, keys) => {
  const output=[];
  for(const [key, value] of Object.entries(obj)){
  if(!keys.includes(key)){
     output.push([key,value]);
    }
  }
 return Object.fromEntries(output);
}

Solution 16 - Javascript

No answer seemed to allow nested path specifications using dot notation. Here's a solution for that:

const omit = (obj, keys) => {
  if (!keys.length) return obj;
  const key = keys.pop();
  const parts = key.split(".");
  if (parts.length > 1) {
    const { [parts[0]]: todo, ...rest } = obj;
    return {
      ...omit(rest, keys),
      [parts[0]]: omit(todo, [parts[1]]),
    };
  }
  const { [key]: omitted, ...rest } = obj;
  return omit(rest, keys);
};
    
var obj = {
  a: 1,
  b: 2,
  c: 3,
  d: {
    c: 3,
    e: 5
  }
};
console.log(omit(obj, ['b', 'd.c']));

Solution 17 - Javascript

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});

Solution 18 - Javascript

For removing one property from an object, you could use the keyword delete.
You even don't need to check if the property exists in the object.

const testObject = { a: "A", b: "B" }
delete testObject.a

//output
{
  b: "B"
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAwebView Question on Stackoverflow
Solution 1 - JavascriptCraig GehringView Answer on Stackoverflow
Solution 2 - JavascriptgyreView Answer on Stackoverflow
Solution 3 - JavascriptEddie CooroView Answer on Stackoverflow
Solution 4 - JavascriptGeoffrey HaleView Answer on Stackoverflow
Solution 5 - JavascriptBrigandView Answer on Stackoverflow
Solution 6 - Javascriptghiles ybeggazeneView Answer on Stackoverflow
Solution 7 - Javascriptwill FarrellView Answer on Stackoverflow
Solution 8 - JavascriptGrant ZvolskyView Answer on Stackoverflow
Solution 9 - Javascriptguest271314View Answer on Stackoverflow
Solution 10 - Javascriptrorymorris89View Answer on Stackoverflow
Solution 11 - JavascriptMitsakosView Answer on Stackoverflow
Solution 12 - JavascriptAndrés AndradeView Answer on Stackoverflow
Solution 13 - Javascriptajai JothiView Answer on Stackoverflow
Solution 14 - JavascriptAlex YoungView Answer on Stackoverflow
Solution 15 - JavascriptMasih JahangiriView Answer on Stackoverflow
Solution 16 - JavascriptMike CroweView Answer on Stackoverflow
Solution 17 - JavascriptLeybView Answer on Stackoverflow
Solution 18 - JavascriptmstfgueclueView Answer on Stackoverflow