0

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"
}
1
  • The question shows absolutely no effort in solving the problem. I don't think "pls solve for me" kind of questions are acceptable at SO. Commented Jun 10, 2019 at 8:52

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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.