I have this:
let obj= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
I want to console.log(JSON.stringify(obj_without_Cow)), so this would be logged:
{
'Cat' : 'Meow',
'Dog' : 'Bark'
}
I could delete Cow, destructure with rest, or use several other approaches, but I was wondering if there is a way to only modify what is passed to console.log, as shown above. That is, without extra code outside of console.log().
Analogically, if I was logging a str = 'xxxyyy', I could have all 'x's removed: console.log(str.replaceAll('x','')), it is intuitive to try console.log(delete obj.Cow) which, however, return true or false, not the modified object.
without extra code outside of
console.log().
An IIFE does wonders for one-liners:
console.log( (({Cow, ...withoutCow}) => JSON.stringify(withoutCow))(obj) );
Alternatively, you can use the replacer parameter to JSON.stringify:
console.log(JSON.stringify(obj, (key, val) => key == 'Cow' ? undefined : val));
It seems that you need a console.log interceptor:
console.log = (() => {
const logger = console.log;
return function (...args) {
if (typeof args[0] === 'object')
args[0] = Object.fromEntries(Object.entries(args[0]).filter(([key]) => !key.includes('Cow')));
else if (typeof args[0] === 'string')
args[0] = args[0].replaceAll('x','');
return logger.apply(this, args);
};
})();
let obj = {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
let str = 'xxxyyy';
console.log(obj);
console.log(str);
If you are using Underscore.js or Lodash, there is a function 'omit' that will do it.
https://lodash.com/docs#omit
const thisIsObject= {
'Cow' : 'Moo',
'Cat' : 'Meow',
'Dog' : 'Bark'
};
console.log(_.omit(thisIsObject,'Cow'));
=> {'Cat' : 'Meow', 'Dog' : 'Bark'}
Or you can create your own omit function from pure JavaScript.
const omit = (inputObject, removedKeys) =>
Object.keys(inputObject)
.filter((key) => !removedKeys.includes(key))
.reduce((obj, key) => {
obj[key] = inputObject[key];
return obj;
}, {});
console.log(omit(thisIsObject,'Cow'));
=> {'Cat' : 'Meow', 'Dog' : 'Bark'}