Skip to content

Instantly share code, notes, and snippets.

@Ambratolm
Last active August 14, 2021 16:14
Show Gist options
  • Save Ambratolm/9b106e6fe584ff6a733bdf8f1c26362a to your computer and use it in GitHub Desktop.
Save Ambratolm/9b106e6fe584ff6a733bdf8f1c26362a to your computer and use it in GitHub Desktop.
Omits fields of an object in JavaScript.
// Function
function omit(obj = {}, fields = []) {
const rObj = { ...obj };
for (const prop in obj) {
if (fields.includes(prop)) {
delete rObj[prop];
}
}
return rObj;
}
// Test
const user = {
id: 0,
name: "Mohamed",
values: [ 1, 2, 3, 4, 5 ]
}
console.log(omit(user, ["id", "values"])) // Outputs: { name: "Mohamed" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment