Skip to content
Advertisement

console.log() an object stripped of selected keys

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.

Advertisement

Answer

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));
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement