Creating a Key/Pair Object Using jQuery and Some Inputs

Creating a Key/Pair Object Using jQuery and Some Inputs

I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.

Here is the javascript code I have so far:

<script type="text/javascript" language="javascript">
    $(document).ready(function () {

        var items = [];

        $(".item").each(function () {
            var productKey = $(this).find("input[type='hidden']").val();
            var productQuantity = $(this).find("input[type='text']").val();
            items.addKey(productKey, productQuantity); ?
        });

        // 1. Grab the values of each ammount input and it's productId.

        // 2. Send this dictionary of key pairs to a JSON action method.

        // 3. If results are OK, reload this page.
    });
</script>

The comments I wrote are just guidelines for me on how to proceed.

Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.

I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.

4 Answers

items[productKey] = productQuantity;

In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:

var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"

So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:

items[productKey] = productQuantity;
items[productKey]; // => productQuantity

You can add anonymous objects to the items array like:

items.push({
    key: productKey,
    quantity: productQuantity
});

Then access them later as items[0].key or items[0].quantity.

Also you can use JQuery.data method and like that you can also get rid of those hidden.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.