I'm facing a challenge with my JSON structure:
people = [{"id":"0001","title":"Mr","name_first":"Bob","name_last":"Edwards","address1":"2 ford road","address2":null,"address3":null,"town":"Bedford","county":"Bedfordshire","postcode":"Mk16hd","telephone1":"01827485999","telephone2":null,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3d303d1f3a323e3633713c30">[email protected]</a>"},
{"id":"8003","title":"Mr","name_first":"Joe","name_last":"Bloggs","address1":"186 Bath Road","address2":null,"address3":null,"town":null,"county":null,"postcode":null,"telephone1":"01827485648","telephone2":null,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80eaefe5c0e5ede1e9ecaee3efed">[email protected]</a>"},
{"id":"R005","title":"Mr","name_first":"Foo","name_last":"Bar","address1":null,"address2":null,"address3":null,"town":null,"county":null,"postcode":null,"telephone1":"01827485647","telephone2":null,"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3930301f3a32">[email protected]</a>"}];
Tackling this issue involves looping through the JSON and creating buttons:
for (var key in people) {
if (people.hasOwnProperty(key)) {
var person = people[key];
var button = document.createElement('button');
button.innerHTML = '<span class="left-body">Edit</span>';
button.onclick = function() { editPerson(key); return false; };
}
}
However, I encounter an unexpected behavior when clicking the buttons:
function editPerson(index) {
console.log(index);
return false;
}
My question now is: How can I properly pass the key value of each JSON item into the editPerson()
function?