TIL how to hide certain properties in stringified data
POSTED ON:
JSON.stringify
had a second argument which is largely unknown. It's called the replacer and it's a function or array that decides which data to keep in the output and which not to.
replacer (Optional)
A function that alters the behavior of the stringification process, or an array of strings or numbers naming properties of value that should be included in the output. If replacer is null or not provided, all properties of the object are included in the resulting JSON string.
MDN entry for JSON.stringify()
const user = {
name: 'John',
password: '12345',
age: 30
};
console.log(JSON.stringify(user, (key, value) => {
if (key === 'password') {
return;
}
return value;
}));
// result
// {"name":"John","age":30}
Fancy!
A better refactor to remove specific keys:
const user = {
name: 'John',
password: '12345',
age: 30,
gender: 'male'
};
function stripKeys(...keys) {
return (key, value) => {
if (keys.includes(key)) {
return;
}
return value;
};
}
const stripUser = JSON.stringify(user, stripKeys('password', 'gender'))
console.log(stripUser);
// {"name":"John","age":30}
via 5 Secret features of JSON in JavaScript you didn't know about
Related TILs
Tagged: mdn