Skip to content

Instantly share code, notes, and snippets.

@bj7
Last active March 25, 2017 16:38
Show Gist options
  • Save bj7/ce63c0a7f2ebc8d29f43db00eccca369 to your computer and use it in GitHub Desktop.
Save bj7/ce63c0a7f2ebc8d29f43db00eccca369 to your computer and use it in GitHub Desktop.
Small recursive routine to deeply parse any object and convert all arrays into string lists. Helps when dealing with servers that limit http data parameters.
/**
* Recurse object and stringify any arrays. This helps when passing paremeters
* to a server since some servers may limit the number of distinct items in http requests.
* @param {Object} obj Object to parse
* @return {Object} Return the parsed object
*/
function jsonDeepStringify(obj) {
if (Object.prototype.toString.call(obj) == '[object Array]') {
obj = obj.join(',');
} else if (typeof (obj) == 'object') {
for (let i in obj) {
if (typeof (obj[i]) == 'object') {
obj[i] = jsonDeepStringify(obj[i]);
}
}
}
return obj;
}
@bj7
Copy link
Author

bj7 commented Mar 25, 2017

Edit to better handle cases when the incoming parameter is already an object.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment