Today I Learned - Rocky Kev

TIL how to hide certain properties in stringified data

POSTED ON:

TAGS:

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:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.