bigLdot
bigLdot

Reputation: 173

Loop through items in JQuery and output JSON object

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"
}

Upvotes: 0

Views: 130

Answers (2)

steven7mwesigwa
steven7mwesigwa

Reputation: 6720

Try this:

1. Simply Create an empty object i.e

let result = {};

2. Then write:

 cart_data.forEach(i => Object.assign(result ,i))

3. Finally return the result

return result;

Full code

    function getCartItems() {
        cart_data = [];
        let result = {};
        $('.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);
        });

        cart_data.forEach(i => Object.assign(result ,i))
        return result ;
    }

Good Luck :)

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337580

You're creating an array when your target output is an object. Instead of pushing the new object to an array you can instead define a parent object and set the key/value pairs within it, like this:

function getCartItems() {
  var cart_data = {};
  $('.cart-item').each(function() {
    cart_data[$(this).data('sku')] = $(this).find('input.cart-item-qty').val();
  });
  return cart_data;
}

Upvotes: 1

Related Questions