JSON.stringify () not working as expected
I have used JSON.stringify()
many times and I am aware of some problems such as (described in here ):
- cycles
- too deep objects
- too long arrays
However, I came across an incorrect line of operation on an object that looks like this:
After running JSON.stringify (obj) in the console, I get this.
"[{"$$hashKey":"object:103",
"ProductCategories": [{"Id":2,"ShopProductCategoryName":"Drink","isSelected":true}
{"Id":3,"ShopProductCategoryName":"Food","isSelected":true}]
}]"
He only builds ProductCategories
and $$hashKey
, which is completely unexpected.
Solution attempts
If I create a new object from obj
and string it, it returns correct 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.
I used the code to push the object to the web api, but of course the path is not what I want.
As I can see,
- There are no cycles.
- It's not too deep. (only has a depth of 3)
So I cannot figure out what is wrong.
source to share
Well, I suggest you create a function that clones your object without a property $$hashKey
, which was set by angular I think:
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;
}
After you clone your object without $$hashKey
, you can flatten it without any problem.
source to share