Stringify ( ) - Optional Parameters
Video
JavaScript Notes
JavaScript
// Lesser known features when using JSON.stringify( )
let obj = {name: "Walter",
last: "Sobchack",
age: 50,
angry: true,
betscore: 200,
armed: true};
let log = console.log;
let str;
str = JSON.stringify(obj);
log('1', str);
// USING AN ARRAY TO FILTER THE OBJECT
str = JSON.stringify(obj, ['age', 'angry', 'last']); // allows you to specify what you want from the object
log('\n2', str);
// USING A FUNCTION TO FILTER
function replace(key, val) {
if (typeof val === 'string'){
return undefined;
} else {
return val;
}
}
str = JSON.stringify(obj, replace);
log('\n3', str); // will return all properties except those with a string value
// PLACING CHARACTERS BEFORE PROPERTIES
str = JSON.stringify(obj, null, 4); // returns object with 4 spaces before each property
log('\n4', str);
Feedback
Submit and view feedback