I suspect this is an easy problem, but I am a bit new to js and can't find the solution.
Basically, when I pass a JSON string to a function and then attempt to iterate through the passed variable, it treats it like a literal string rather than an array.
With this function:
function build_codes_long(codes) {
var codes_long_text = "";
for(var i =0;i < codes.length-1;i++) {
var code = codes[i];
codes_long_text += "<p>" + code['id'] + " = " + code['del'] + "</p>";
}
return codes_long_text;
}
When I pass a JSON string to it like:
[{"id":"1","del":"0","clip":"1"},{"id":"2","del":"0","clip":"1"}]
It evaluates each character in the string, rather than each item in the array. So it loops 65 times instead of 2, returning something like:
undefined = undefined
I understand the problem with the returned values; it's the treating the array like a literal string I don't understand. Thanks!
It's because you're not looping through an object; you're looping through a string and getting each letter as a result.
You need to convert the JSON string to an object first:
var myObject = JSON.parse(myJsonString);
var codesLongText = build_codes_long(myObject);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With