Last active
May 13, 2018 18:08
-
-
Save CoralSilver/54265046f317a467686e6294034fc8b3 to your computer and use it in GitHub Desktop.
Remove key from object with ES6 destructing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function removeByKey (myObj, deleteKey) { | |
return Object.keys(myObj) | |
.filter(key => key !== deleteKey) | |
.reduce((result, current) => { | |
result[current] = myObj[current]; | |
return result; | |
}, {}); | |
} | |
// Helper function | |
const deleteProperty = ({[key]: _, ...newObj}, key) => newObj; | |
deleteProperty({a:1, b:2}, "a"); | |
// returns {b:2} | |
// Long version | |
const original = { | |
foo: 'bar', | |
stack: 'overflow', | |
}; | |
// If the name of the property to remove is constant | |
const { stack, ...withoutFirst } = original; | |
console.log(withoutFirst); // Will be { "foo": "bar" } | |
// If the name of the property to remove is from a variable | |
const key = 'stack' | |
const { [key]: value, ...withoutSecond } = original; | |
console.log(withoutSecond); // Will be { "foo": "bar" } | |
// To do a deep removal with property names from variables | |
const deep = { | |
foo: 'bar', | |
c: { | |
x: 1, | |
y: 2 | |
} | |
}; | |
const parentKey = 'c'; | |
const childKey = 'y'; | |
// Remove the 'c' element from original | |
const { [parentKey]: parentValue, ...noChild } = deep; | |
// Remove the 'y' from the 'c' element | |
const { [childKey]: removedValue, ...childWithout } = parentValue; | |
// Merge back together | |
const withoutThird = { ...noChild, [parentKey]: childWithout }; | |
console.log(withoutThird); // Will be { "foo": "bar", "c": { "x": 1 } }// es6 helper function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment