使用JSON.Stringify
假如有一个对象具有参数”prop1”, “prop2”, “prop3”。 我们可以通过传递 附加参数 给 JSON.stringify 来选择性地将参数生成字符串,像这样:
var obj = {
'prop1': 'value1',
'prop2': 'value2',
'prop3': 'value3'
};
var selectedProperties = ['prop1', 'prop2'];
var str = JSON.stringify(obj, selectedProperties);
// str
// {"prop1":"value1","prop2":"value2"}
“str” 将只包含选择的参数。
除了传递数组,我们也可以传递函数。
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;
}
最后一个参数,可以修改生成字符串的方式。
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