One Pager Cheat Sheet
- You can create a simplified version of the
JSON.stringify()
method to correctly handle different data types and values in order to successfully "translate" them into JSON strings. - We bold implemented a
stringify
method that handles different data types, such as functions, strings, numbers, booleans, dates, arrays, and objects, returning the corresponding strings ornull
as needed.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
33
}
function stringify(data) {
if (typeof data === "string") {
return `"${data}"`;
}
if (typeof data === "function") {
return undefined;
}
if (data === Infinity || data === -Infinity || data === null
|| data === undefined || typeof data === "symbol") {
return "null";
}
if (typeof data === "number" || typeof data === "boolean") {
return `${data}`;
}
if (data instanceof Date) {
return `"${data.toISOString()}"`;
}
if (Array.isArray(data)) {
const arr = data.map((el) => stringify(el));
return `[${arr.join(",")}]`;
}
if (typeof data === "object") {
const arr = Object.entries(data).reduce((acc, [key, value]) => {
if (value === undefined) {
return acc;
}
acc.push(`"${key}":${stringify(value)}`);
return acc;
}, []);
return `{${arr.join(",")}}`;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.