Im not even sure if I worded the title of what I need correctly, but in a nutshell, I'm trying to loop through a nested js object, extract specific values, combine them with an html template, then append a Div with the result (for an ecommerce site uing snipcart).
This is my code at the moment (which clearly doesnt work)
var comics = {
modern: {
1: {
"data-item-id" : "pun-224",
"data-item-price" : "3.49",
"data-item-url" : "/",
"data-item-description" : "The Punisher issue 224",
"data-item-image" : "/img/modern.jpg",
"data-item-name" : "The punisher 224"
},
2:{
"data-item-id" : "pun-225",
"data-item-price" : "3.49",
"data-item-url" : "/",
"data-item-description" : "The Punisher issue 224",
"data-item-image" : "/img/silver.jpg",
"data-item-name" : "The punisher 225"
}
}
}
$(document).ready(function(){
console.log("hello");
$.each(comics.modern, function() {
var list = $("#comic__list");
list.append(
`<button
class="snipcart-add-item"
data-item-id="${this.data-item-id}"
data-item-price="${this.data-item-id}"
data-item-url="${this.data-item-id}"
data-item-description="${this.data-item-id}"
data-item-image="${this.data-item-id}"
data-item-name="${this.data-item-id}">
Add to cart
</button>`
)
});
});
Just use Object.keys to get the object keys as array and then you can loop through it:
$(document).ready(function(){
$.each(Object.keys(comics.modern), function() {
var currentObject = comics.modern[this];
var list = $("#comic__list");
list.append(
`<button
class="snipcart-add-item"
data-item-id="${currentObject['data-item-id']}"
data-item-price="${currentObject['data-item-id']}"
data-item-url="${currentObject['data-item-id']}"
data-item-description="${currentObject['data-item-id']}"
data-item-image="${currentObject['data-item-id']}"
data-item-name="${currentObject['data-item-id']}">
Add to cart
</button>`
)
});
});
Note: you cannot use object.property-of-the-object when the property contains a dash, instead use object['property-of-the-object']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.