Storing Complex Data
Store entire objects or arrays on elements — useful for attaching API response data to UI cards without re-fetching.
Store entire objects or arrays on elements — useful for attaching API response data to UI cards without re-fetching.
$.getJSON("/api/users", function(users) {
users.forEach(function(user) {
const card = $(`<div class="card user-card">${user.name}</div>`);
card.data("user", user); // attach entire object
$("#container").append(card);
});
});
$(document).on("click", ".user-card", function() {
const user = $(this).data("user");
console.log(user.email, user.role); // full object accessible
});
Storing objects with .data() avoids repeated AJAX calls for data you already have.