willowcheng
10/3/2015 - 3:17 AM

Calculates how much all lamps and wallets would cost me

Calculates how much all lamps and wallets would cost me

// Initial total cost
var totalCost = 0.0;

// Initial AJAX request
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {

        // Serialize response to JSON format
        var response = JSON.parse(xhr.responseText);

        // Get products list
        var products = response.products;

        // Get each product
        for (var i = 0; i < products.length; i++) {

            // For all wallets and lamps
            if (products[i].product_type === "Wallet" || products[i].product_type === "Lamp") {

                var variants = products[i].variants;
                for (var j = 0; j < variants.length; j++) {
                    totalCost += parseFloat(variants[j].price);
                }
            }
        }
        console.log(totalCost);
    }
};
xhr.open('GET', 'http://shopicruit.myshopify.com/products.json');
xhr.send();