Reputation: 1295
I am trying to build a re-usable function for pulling json results and writing back to the page
so far i get the json and when its returned run a function that passes some data the index and the result. That all works fine
The problem is when I went to do an iteration around the result in the function (seen below)
sometimes the data structure could be data.userGroup.form and other times data.userGroup.user and so on
what i have tried to do is pass the name i want to use into the function as the last argument i.e. "user" and the wihin the inner .each call element.name (where name can vary) but this doesnt work. can anyone help?
here is the code
$.when(promise).then(function(result) {
$(result.data.userGroup).each(function(index, element) {
var html = getHTML( ["Name", "Delete"], index, element, "user");
$("#accordion2").append(html);
});
})
function getHTML(array, index, element, name) {
var html = " <div class='accordion-group'>";
html = html + "<div class='accordion-heading'>";
html = html + "<span class='accordian-image'></span>" + element.name + "</a>";
var inner ="";
$(element.name).each(function(i, result) {
inner = inner + "<tr><td>" + result.name + "</td>" ;
});
html = html + inner;
return html;
}
Upvotes: 0
Views: 109
Reputation: 388326
You need to use the bracket notation instead of dot notation as the member operator.
element[name]
Ex
$.when(promise).then(function(result) {
$(result.data.userGroup).each(function(index, element) {
var html = getHTML( ["Name", "Delete"], index, element, "user");
$("#accordion2").append(html);
});
})
function getHTML(array, index, element, name) {
var html = " <div class='accordion-group'>";
html = html + "<div class='accordion-heading'>";
html = html + "<span class='accordian-image'></span>" + element[name] + "</a>";
var inner ="";
$(element.name).each(function(i, result) {
inner = inner + "<tr><td>" + result[name] + "</td>" ;
});
html = html + inner;
return html;
}
Upvotes: 1