Using JSON.Stringify
Let’s say there is an object with properties “prop1”, “prop2”, “prop3”. We can pass additional params to JSON.stringify to selectively write properties of the object to string like:
var obj = {
'prop1': 'value1',
'prop2': 'value2',
'prop3': 'value3'
};
var selectedProperties = ['prop1', 'prop2'];
var str = JSON.stringify(obj, selectedProperties);
// str
// {"prop1":"value1","prop2":"value2"}
The “str” will contain only info on selected properties only.
Instead of array we can pass a function also.
function selectedProperties(key, val) {
// the first val will be the entire object, key is empty string
if (!key) {
return val;
}
if (key === 'prop1' || key === 'prop2') {
return val;
}
return;
}
The last optional param it takes is to modify the way it writes the object to string.
var str = JSON.stringify(obj, selectedProperties, '\t\t');
/* str output with double tabs in every line.
{
"prop1": "value1",
"prop2": "value2"
}
*/
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW