Jump to the editorJAVASCRIPT
JAVASCRIPT JAVASCRIPT JAVASCRIPT
22.2. Stringify without the password field
Easy
Topics
This question is in
22. SerializationA user object comes back from the database with a password hash on it, and somewhere a log line or an API response writes it out with JSON.stringify. Deleting the field from the object would change data other code still uses. The safer fix is to leave the field out while serializing, at every depth, without touching the object.
Write stringifyWithout(value, hiddenKeys, space) in stringify-without.js. It returns what JSON.stringify(value, null, space) would return, except that every object property whose key is in hiddenKeys is left out.
Signature
function stringifyWithout(value, hiddenKeys, space) // returns a string or undefinedvalue: any valueJSON.stringifyaccepts.hiddenKeys(optional): an array of keys to leave out. When it is missing, it is["password"].space(optional): indentation, with the same meaning as the third argument ofJSON.stringify.
Requirements
- A property named
passwordis left out, at the top level, in nested objects and in objects inside arrays. - Everything else is written exactly as
JSON.stringifywrites it, includingundefinedforundefined. - A given
hiddenKeyslist replaces the default. An empty list hides nothing. - Keys are matched exactly:
Passwordandpasswordsare kept. - Only object properties are hidden. Array items are never dropped, even when
hiddenKeysholds an index such as"0", and a hidden word used as a value is kept. - The input is not changed.
- Objects returned by
toJSONare filtered too. - A hidden key that holds an object hides the whole object. Any key can be hidden, including the empty string
"": it hides a property named"", never the whole value. spaceindents the output; a circular structure still throws aTypeError.
Examples
stringifyWithout({ user: "ada", password: "hunter2" });
// '{"user":"ada"}'stringifyWithout({ users: [{ name: "a", password: "1" }, { name: "b", password: "2" }] });
// '{"users":[{"name":"a"},{"name":"b"}]}'stringifyWithout({ password: "p", token: "t", ok: 1 }, ["token"]);
// '{"password":"p","ok":1}'
stringifyWithout({ list: ["a", "b"] }, ["0"]);
// '{"list":["a","b"]}': array items are not object propertiesEnvironment
- Plain JavaScript in a browser page; the tests call the global
stringifyWithoutfromstringify-without.js. JSON.stringifyis allowed and expected. Hiding keys inside aMapor by a pattern is out of scope.
Hints
- Which argument of
JSON.stringifygets to see every key and value on the way out? - Inside that function, how can you tell an object property from an array item?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it
Back to the question
Loading the editor…