Below is the type of data I am getting via ajax.
[{"model": "blogapp.articles", "pk": 1, "fields": {"title": "Rainbow Buildings in Tokyo", "slug": "Rainbow-Buildings-in-Tokyo"}}, {"model": "blogapp.articles", "pk": 2, "fields": {"title": "4 Cool Cube Facades", "slug": "4-Cool-Cube-Facades"}}]
How can I iterate over this data using .each to get the title and the slug for each entry?
The below code gives me a syntax error on the data.
app.js
$(document).ready(function () {
$(".tag-nav-links").on("click", function (e) {
e.stopPropagation();
return $.ajax({
type: "POST",
url: "",
dataType: "json",
data: { filter: `${e.target.textContent}` },
success: function (data) {
var html = "";
$(data).each(function (index, value) {
html += "<h4>{{" + value.title + "}}</h4>";
});
$("trial").append(html);
},
});
});
});
The jQuery function (which you're using like this: $(data)) isn't what you want there. (You may have meant $.each(data, ...), but these days there's no need.) If data really is an array as shown, just use map on it, then join the result together with a blank string:
success: function (data) {
$("trial").append(data.map(value => {
return "<h4>{{" + value.fields.title + "]]</h4>";
}).join(""));
},
If data is really as shown in the screenshot, then it's an object with a data property containing a string of JSON. That's probably a misconfiguration or coding error on the server, current it's returning text something like this:
{"data":"[{\"model\": \"blogapp.articles\", \"pk\": 1,...
when it should be returning something like this:
{"data":[{"model":"blogapp.articles","pk":1,...
Something is pre-stringifying the data before passing it to whatever wraps it in the {"data": ___} wrapper, stringifies it, and returns it.
Until/unless you fix it, you'll have to parse it twice. jQuery is doing one of those for you, but you'll have to do the second one, after which you should be able to use the array:
// Until/unless the server is fixed
success: function (data) {
data = JSON.parse(data.data); // *** Second parse
$("trial").append(data.map(value => {
return "<h4>{{" + value.fields.title + "]]</h4>";
}).join(""));
},
If you fix the server so it's not double-stringifying, you'd use data.data instead (since data is your parameter name, and it refers to an object with a data property that has the array you want to use):
// After the server is fixed
success: function (data) {
$("trial").append(data.data.map(value => {
// ^^^^^^^^^
return "<h4>{{" + value.fields.title + "]]</h4>";
}).join(""));
},