使用 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) {
// 第一個數值是整個物件,key 是空的字串
if (!key) {
return val;
}
if (key === 'prop1' || key === 'prop2') {
return val;
}
return;
}
最後一個可選參數式是修改物件寫入字串的方式。
var str = JSON.stringify(obj, selectedProperties, '\t\t');
/* str 每個輸出會有 doube tabs。
{
"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