I have a JavaScript function that creates an empty string, grabs key values, converts them to their html form which is what I want to print and adds break lines. I want each line to have its own check box where I have $("#checkboxConsent). It just prints out object object, its html form. Is there a better way to do this?
var consentString = "";//creating empty string for consents
for(var grabbingKeyLines in data.consentText.consentLines)
consentString += '<br>' + $('#checkBoxConsent') + (data.consentText.consentLines[grabbingKeyLines] + '<br>')
}
$('#stateConsentLines').html(consentString);//show string
2
Answers
try to use
$("#checkBoxConsent").clone().attr('id', '').outerHTML()
instead of$("#checkBoxConsent")
:$("#checkBoxConsent").clone().attr('id', '').outerHTML()
this clones the example checkbox to a new element and remove itsid
so it wont be duplicated than getthe html text of the element byouterHTML()
.What you are showing for your JSON (
[0: "some text", 1 : "more text"]
) is not valid JSON.[]
denotes an array and arrays have numeric indices, not keys.{}
denotes an object and objects have string keys.One simple way to know that you have valid JSON is to create the JSON yourself using
JSON.stringify()
as in this example:Given what you are showing in your string, it seems like you need an array, rather than an object (you are showing numeric indices that go with the data).
Next, even if your string was valid JSON, you’d need to pass it into
JSON.parse()
in order to turn it back into a JavaScript array or object before you can work with it as such.Now all of that is just to get you to a point where you have either an array or an object that you can work with in JavaScript. To your specific question, you then need to iterate through that array or object to access the individual elements that it contains.