Aeromax Aeromax - 24 days ago 9
jQuery Question

only get json objects with a matching key

So what I want to do is rather simple. I have a site where comments are displayed, and I have an admin page that allows an admin to delete comments. However I need comments to be hidden before they are reviewed.

This script grabs each object in my json file and displays them:

$.getJSON("data/comments.json", function(data) {
var number = [];
$.each(data, function(index, d) {
number.push("<div class='comment' id='" + index + "'>" + "<div class='comment-text'>" + d.comment + "</div>" + "<img class='comment-image' src='data/upload/" + d.img + "'>" + "<div class='comment-identifier'><span class='comment-name'>" + "– " + d.name + "</span>" + "<span class='comment-department'>" + ", " + d.department + "</span></div>" + "</div>");
});
$("<div/>", {
"id": "comment-container",
html: number.join("")
}).appendTo("#comment-layout");
});


Each json object will have a key of "approved: false" applied to it upon creation. How can I have the above script only pull objects with a "approved: true" on them?

Answer

You can check if the comment is approved or not in the $.each function.

$.each(data, function(index, d) {
   if(d.approved){
        number.push("<div class='comment' id='" + index + "'>" + "<div class='comment-text'>" + d.comment + "</div>" + "<img class='comment-image' src='data/upload/" + d.img + "'>" + "<div class='comment-identifier'><span class='comment-name'>" + "– " + d.name + "</span>" + "<span class='comment-department'>" + ", " + d.department + "</span></div>" + "</div>");
   }
});