Search code examples
jqueryobjectnestedextendliterals

Js: Adding nested object literal items -- can't figure it out


Here is my code:

Cart = {
    items: {
        id1: { cost: 55 },
        id3: { cost: 20 },
        id2: { cost: 15 }
    },

    blah blah blah
}

Now I want to add values to Cart.items with dynamic key & value and I'm stuck.

var id = 5;
Cart.items["id"+id].cost = 20;

I'm also using the jquery library so I'm not sure if .extend is better suited for this.

Any help would be greatly appreciated, Thanks!


Solution

  • Cart.items["id"+id] may not exist. Add this check first:

    if (!Cart.items.hasOwnProperty("id" + id) {
       Cart.items["id" + id] = {};
    }
    

    Then, you can add keys/values at will at that level.