To start, gather all the keys from the initial object and store them in an array
['fname', 'lname', 'pin', ...] // keys from `obj`
Next, utilize .filter()
on this array to filter out any keys that are present in the arr
of keys to be excluded. This will result in an array of keys to keep, which can then be transformed into an array of [key, value]
pairs. With this key-value pair array, you can then use Object.fromEntries()
to generate your final object:
const obj = {
'fname': 'test text',
'lname': 'test text',
'pin': 856,
'address1': 'test text',
'address2': 'test text',
'city': 'test text',
'mob1': 35343434343,
'mob2': 34343434343
};
const arr = ['fname', 'lname', 'mob1', 'address1']; // keys to exclude
const keys = Object.keys(obj).filter(key => !arr.includes(key));
const res = Object.fromEntries(keys.map(key => [key, obj[key]]));
console.log(res);
If there are a significant number of keys to exclude, it is advisable to create a Set first and then utilize .has()
instead of .includes()
for efficient lookup within the .filter()
callback:
const obj = {
'fname': 'test text',
'lname': 'test text',
'pin': 856,
'address1': 'test text',
'address2': 'test text',
'city': 'test text',
'mob1': 35343434343,
'mob2': 34343434343
};
const set = new Set(['fname', 'lname', 'mob1', 'address1']); // keys to exclude
const keys = Object.keys(obj).filter(key => !set.has(key));
const res = Object.fromEntries(keys.map(key => [key, obj[key]]));
console.log(res);
Lastly, in case the keys in array2
are fixed, you can make use of destructuring to extract the keys you wish to exclude, and then utilize the rest pattern ...
to get an object without those specific keys. However, this method only works with static keys:
const obj = { 'fname': 'test text', 'lname': 'test text', 'pin': 856, 'address1': 'test text', 'address2': 'test text', 'city': 'test text', 'mob1': 35343434343, 'mob2': 34343434343 };
const {fname, lname, mob1, address1, ...res} = obj;
console.log(res);