I'm trying to create a function that clears up a JSON object by removing jQuery objects and null objects, strings.
CODE:
JSON.clean = function (object) {
/// <summary>Removes jQuery and null values from json object.</summary>
var filter = function (obj, doArrays) {
$.each(obj, function (key, value) {
if (value === "" || value === null) {
delete obj[key];
} else if (Object.prototype.toString.call(value) === '[object Object]') {
filter(value);
} else if (doArrays || Array.isArray(value)) {
obj[key] = filterArray(value);
}
});
return obj;
};
var filterArray = function (obj) {
var result = [];
for (var i = 0; i < obj.length; i++) {
result.push(filter(obj[i], false));
}
return result;
};
var result;
if ($.isArray(object)) {
result = [];
for (var i = 0; i < object.length; i++) {
result.push(filter(object[i]));
}
} else {
result = filter(object);
}
return result;
};
PROBLEM:
The code crashes when trying to clean up arrays within the JSON object.
I know that it's wrong to alter a Array like this but this is purely meant for JSON objects with in an array.
My suggestion to this problem would be to wait untill the cleaning of an Array is completed.
I don't know how to achieve this in Javascript so i'm hoping anyone of you can help!
I've used this source for the main idea:
How do I remove all null and empty string values from a json object?