Last active
December 25, 2015 20:08
-
-
Save jwaltonmedia/7032226 to your computer and use it in GitHub Desktop.
recursive javaScript function used to pull all string values from a JSON Object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getStringsFromJson(json) { | |
var values = []; | |
for (var prop in json) { | |
(function findStr(obj) { | |
if (typeof obj == 'string') { | |
values.push(obj); | |
} else if (obj instanceof Array) { | |
for (var i = obj.length - 1; i > -1; i--) { | |
var val = obj[i]; | |
findStr(val); | |
} | |
} else if (typeof obj == 'object' && obj instanceof Object) { | |
values = values.concat(getStringsFromJson(obj)); | |
} | |
})(json[prop]); | |
} | |
return values; | |
}; | |
function returnStringsFromJson(json) { | |
var values = []; | |
for (var node in json) { | |
if (json.hasOwnProperty(node)) { | |
if (typeof json[node] === 'string') { | |
values.push(json[node]); | |
} | |
if (typeof json[node] === 'object' && json[node] instanceof Object) { | |
values = values.concat(returnStringsFromJson(json[node])); | |
} | |
} | |
} | |
return values; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment