[英]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:我想
console.log(JSON.stringify(obj_without_Cow))
,所以这将被记录:
{
'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.我可以
delete
Cow,使用 rest 进行解构,或者使用其他几种方法,但我想知道是否有一种方法可以只修改传递给 console.log 的内容,如上所示。 That is, without extra code outside of console.log()
.也就是说,在
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.类似地,如果我正在记录
str = 'xxxyyy'
,我可以删除所有 'x': console.log(str.replaceAll('x',''))
,尝试console.log(delete obj.Cow)
但是,它返回 true 或 false,而不是修改后的 object。
without extra code outside of
console.log()
.在
console.log()
之外没有额外的代码。
An IIFE does wonders for one-liners: IIFE 为单线创造了奇迹:
console.log( (({Cow, ...withoutCow}) => JSON.stringify(withoutCow))(obj) );
Alternatively, you can use the replacer
parameter to JSON.stringify
:或者,您可以使用替换
replacer
JSON.stringify
:
console.log(JSON.stringify(obj, (key, val) => key == 'Cow' ? undefined : val));
It seems that you need a console.log
interceptor:看来您需要一个
console.log
拦截器:
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.如果你使用
Underscore.js
或Lodash
,有一个 function 'omit' 可以做到。 https://lodash.com/docs#omit 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.或者您可以从纯 JavaScript 创建自己的
omit
function。
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'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.