0

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>`
        )    

    
});

});

1 Answer 1

2

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']

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.