Filter object properties by key in JavaScript
Let’s say you have
{ item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }
and want to get rid of item2
. How do you do that in JavaScript?
const data = { item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }; const { item2, ...newData } = data;
Now, newData contains:
{ item1: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } };
Or, if you have the key stored as a string in a variable called key
:
const key = 'item2'; const { [key]: _, ...newData } = data;
A simple utility function would look like this:
function removePropFromObject(obj, prop) { const { [prop]: _, ...rest } = obj return { ...rest } }
Using a list of allowed keys
This will make a shallow copy with the allowed properties (but won’t copy the properties themselves).
const raw = { item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }; const allowed = ['item1', 'item3']; const filtered = Object.keys(raw) .filter(key => allowed.includes(key)) .reduce((obj, key) => { obj[key] = raw[key]; return obj; }, {}); console.log(filtered);
You can also use the object spread operator to create a series of objects without mutating them
const raw = { item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }; const allowed = ['item1', 'item3']; const filtered = Object.keys(raw) .filter(key => allowed.includes(key)) .reduce((obj, key) => { return { ...obj, [key]: raw[key] }; }, {}); console.log(filtered);
By mutating the original object:
const raw = { item1: { key: 'sdfd', value:'sdfd' }, item2: { key: 'sdfd', value:'sdfd' }, item3: { key: 'sdfd', value:'sdfd' } }; const allowed = ['item1', 'item3']; Object.keys(raw) .filter(key => !allowed.includes(key)) .forEach(key => delete raw[key]); console.log(raw);