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?
In modern environments you can use this code snippet:
function omit(key, obj) {
const { [key]: omitted, ...rest } = obj;
return rest;
}
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>
const {omittedPropertyA, omittedPropertyB, ...remainingObject} = originalObject;
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/
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]})));
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});
const { bar, baz, ...qux } = foo
Now your object qux
has all of the properties of foo
except for bar
and baz
.