I'm trying to create a simple JSON object from a list of elements and output it in a specific format (to be sent to a server).
I'm unsure exactly how to properly execute this to get the output I need. So far I've looped through the items and got the relevant data:
function getCartItems() {
cart_data = [];
$('.cart-item').each(function(){
var sku = $(this).data('sku'),
qty = $(this).find('input.cart-item-qty').val();
item = {};
item[sku] = qty;
cart_data.push(item);
});
return cart_data;
}
This gives me an array of items as expected:
[
{"sku1":"1"},
{"sku2":"1"}
]
But what I'M TRYING TO GET is the following format:
{
"sku1":1,
"sku2":1
}
This output is then being used in a function like this:
function getData() {
var cart_items = getCartItems();
return JSON.stringify({"items":cart_items,"ref":"123"});
}
Where the final output will be:
{
"items": {
"sku1": 1,
"sku2": 1
},
"ref": "123"
}