Reputation: 6612
I have the following code which retrieves data with a JSON request:
// Replace home page template wildcards with data from database (JSON)
$.getJSON("mvc/models/home.php?action=getpagecontent&&jsoncallback=?", function(data) {
// Set markup identifiers
var identifiers = new Array();
identifiers[0] = "introheader1";
identifiers[1] = "introtext1";
// Replace markup on page
for (var x = 0; x < data.length; x++) {
if (data[x].introheader1 != undefined){
$(".introheader1").replaceWith(data[x].introheader1);
}
if (data[x].introtext1 != undefined){
$(".introtext1").replaceWith(data[x].introtext1);
}
}
});
This works fine, but is a pain if there a lot of elements returned. So instead of this for every element:
if (data[x].introheader1 != undefined){
$(".introheader1").replaceWith(data[x].introheader1);
}
I want to make it dynamic by replacing the hard coded values with the values from the identifiers array, like this, so I only have to have one and can loop through:
if (data[x].identifiers[0] != undefined){
$("." + identifiers[0]).replaceWith(data[x].identifiers[0]);
}
But it gives an error at the "data[x]." replacements. How can I do this? Thanks!
Upvotes: 0
Views: 205
Reputation: 18344
Change your for
to this:
for (var x = 0; x < data.length; x++) {
for(var prop in data[x]){
$("."+prop).replaceWith(data[x][prop]);
}
}
Hope this helps. Cheers
Upvotes: 1