I have a section of my code, that is supposed to take the data from the JSON file and turn it into individual buttons which will later be styled. I want the button to look like this:
<button>NAME WOULD BE HERE; INTERESTS WOULD BE HERE</button>
The code I have to do this is as follows:
function load() {
var arrayInput = '[{"name" : "Jeff", "interests" : "3"}, {"name" : "Harry", "interests" : "2"}, {"name" : "Bob", "interests" : "coding"}, {"name" : "Jay", "interests" : "coding"}]';
var array = JSON.stringify(arrayInput);
var resultBoxs = document.getElementById("resultBoxs");
for (var i = 0; i < array.length; i++) {
var buttonCreate = document.createElement("button");
buttonCreate.type = "checkbox";
buttonCreate.innerHTML = array[i]
resultBoxs.appendChild(buttonCreate);
}
}
<body onload="load()">
<div id="resultBoxs"></div>
</body>
The result for the code when I have it set to stringify is what you see in figure 1. Figure 1 The result for the code when I have it set to parse the data is what you see in figure 2. It constantly creates more and more buttons for the data, which I do not want. I want it to create one button that follows the template above, for each person/name in the data list. Figure 2
Thanks.
Advertisement
Answer
Very close! Two things:
First and major problem was, you were calling JSON.stringify(arrayInput);
and not JSON.parse(arrayInput);
, the parse function turns JSON string into a object.
Secondly, the buttonCreate.innerHTML = array[i]
needed to be buttonCreate.innerHTML = array[i].name + "; " + array[i].interests;
, this new code is actually pulling the properties out of your array element whereas your were just putting the whole object into the innerHTML; [Object object] gets printed out on your buttons.
Here is what you’re looking for:
function load() {
var arrayInput = '[{"name" : "Jeff", "interests" : "3"}, {"name" : "Harry", "interests" : "2"}, {"name" : "Bob", "interests" : "coding"}, {"name" : "Jay", "interests" : "coding"}]';
var array = JSON.parse(arrayInput);
var resultBoxs = document.getElementById("resultBoxs");
for (var i = 0; i < array.length; i++) {
var buttonCreate = document.createElement("button");
buttonCreate.type = "checkbox";
buttonCreate.innerHTML = array[i].name + ";" + array[i].interests;
resultBoxs.appendChild(buttonCreate);
}
}
<body onload="load()">
<div id="resultBoxs"></div>
</body>