I'm trying to write a function that will run encodeURIComponent on arrays or objects regardless of the depth. It all seems to go well until I return the final result.
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
<script>
function encodeURI_array($Array) {
$Result = [];
if($Array !== null && typeof $Array === 'object') {
//for(var key in $Array) {
Object.keys($Array).forEach(function (key) {
if($Array[key] !== null && typeof $Array[key] === 'object') {
console.log("encode array: " + key + " : " + $Array[key]);
$Result[key] = encodeURI_array($Array[key]);
} else {
$Result[key] = encodeURIComponent($Array[key],"UTF-8").replace(/\+/g, ' ').replace("%26","&").replace("%2C",",");
console.log("encode strings: " + key + " : " + $Result[key]);
}
});
console.log("Final result");
console.log($Result);
return $Result;
} else {
$Result = encodeURIComponent($Array,"UTF-8").replace(/\+/g, ' ').replace("%26","&").replace("%2C",",");
console.log("encode string: " + $Result);
return $Result;
}
}
$TestArray = [{"Key1":"Value1"},{"Key2":"Value2"},{"Key3":"Value3"}];
$TestArray2 = {"Key":"Value"};
(encodeURI_array($TestArray));
//console.log(encodeURI_array($TestArray2));
</script>
For this script, the very last result returns only the last object in the array when it should be returning an array of objects.