Targeting and Looping data from Arrays of Object
by demos12
HTML
<span id="prod_attribute" data-product_variations='[{"attributes":{"attribute_colour":"brown", "attribute_pa_size":"small"}, "display_price": 255}, {"attributes":{"attribute_colour":"blue", "attribute_pa_size":"large"}, "display_price": 355}]'></span>
<table class="variations">
<tr>
<td class="value">
<div class="swatchinput">
<div data-option="black">
<span>Black</span>
</div>
</div>
<div class="swatchinput">
<div data-option="white-gray">
<span>White Gray</span>
</div>
</div>
</td>
</tr>
<tr>
<td class="value">
<div class="swatchinput">
<div class="attribute_cushion-type_SEAT PAD ONLY" data-option="SEAT PAD ONLY">
<span>SEAT PAD ONLY</span>
</div>
</div>
<div class="swatchinput">
<div class="attribute_cushion-type_CUSHION SET" data-option="CUSHION SET">
<span>CUSHION SET</span>
</div>
</div>
<div class="swatchinput">
<div class="attribute_cushion-type_NO CUSHION" data-option="NO CUSHION">
<span>NO CUSHION</span>
</div>
</div>
</td>
</tr>
</table>
CSS
.swatchinput {
padding: 5px 10px;
width: 130px;
border: 1px solid #333;
margin: 10px;
border-radius: 5px;
display: inline-block;
}
JavaScript
var newArray = jQuery('[data-product_variations]').data();
var attrPrice = newArray.product_variations;
console.log(attrPrice);
$.each(attrPrice, function( key, value ) {
console.log('Size: ' + value.attributes['attribute_pa_size'] + ' | price: ' +value.display_price);
$('.variations tr td div.swatchinput').each(function(){
var size = value.attributes['attribute_pa_size'];
var price = value.display_price;
var dataOptionSize = $("[data-option").data();
//processing this row
//how to process each cell(table td) where there is checkbox
console.log("attribute_pa_size_" + size );
if($('div', this).hasClass( "attribute_pa_size_" + size)) {
$('span', this).append("<div class='varPrice' style='margin-top: 5px;'>$" + price + ".00</div>");
$('span .varPrice:not(:first-child)').css('display', 'none');
}
// end of cell row processing
});
});
//console.log(filterObj);
//alert( newArray );