[英]JSON.stringify() Does Not Work As Expected
我多次使用JSON.stringify()
並且我知道一些問題,例如(在這里描述):
但是,我在對象上面臨不正確的stringify操作,就像這樣:
在控制台上運行JSON.stringify(obj)后,我得到了。
"[{"$$hashKey":"object:103",
"ProductCategories": [{"Id":2,"ShopProductCategoryName":"Drink","isSelected":true}
{"Id":3,"ShopProductCategoryName":"Food","isSelected":true}]
}]"
它只對ProductCategories
和$$hashKey
進行字符串化,這是完全出乎意料的。
如果我從obj
創建新對象並對其進行字符串化,則返回正確的JSON。
var newObj = { // Creates new object with same properties.
AllProductCategories: obj.AllProductCategories,
Id: obj.Id,
LabelName: obj.LabelName,
Percentages: obj.Percentages,
ProductCategories: obj.ProductCategories
}
JSON.stringify(newObj); // Returns correct JSON.
我使用代碼強制將對象發送到web api,但當然不是我想要的方式。
我看,
因此,我無法弄清楚出了什么問題。
好吧,我建議你創建一個克隆你的對象的函數,而不使用由angular設置的$$hashKey
屬性:
function cloneObj (obj) {
var cloned = JSON.parse(JSON.stringify(obj));
delete cloned.$$hashKey;
for(var key in cloned) {
if(typeof cloned[key] === 'object') {
cloned[key] = cloneObj(cloned[key]);
}
}
return cloned;
}
在沒有$$hashKey
情況下克隆對象后,您可以$$hashKey
進行字符串化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.