How to remove all properties from object except specified key with JavaScript?

Sometimes, we want to remove all properties from object except specified key with JavaScript.

In this article, we’ll look at how to remove all properties from object except specified key with JavaScript.

How to remove all properties from object except specified key with JavaScript?

To remove all properties from object except specified key with JavaScript, we can use some object and array methods.

For instance, we write:

const validKeys = ['a', 'b', 'c'];
const userInput = {
  "a": 1,
  "b": 2,
  "c": 3,
  "d": 4,
  "e": 5
}

const filteredEntries = Object.entries(userInput).filter(([key]) => validKeys.includes(key))
const newUserInput = Object.fromEntries(filteredEntries)
console.log(newUserInput)

to call Object.entries to return an array of key-value pairs in userInput as a nested array.

Then we call filter with a callback to return the key-value pair arrays with key that’s in validKeys.

Next, we call Object.fromEntries with filteredEntries to return the object created from the key-value pair arrays in filteredEntries.

Therefore, newUserInput is:

{
  a: 1,
  b: 2,
  c: 3
}

Conclusion

To remove all properties from object except specified key with JavaScript, we can use some object and array methods.