Search code examples
javascriptjqueryextend

Is there a shorter way to define an object structure with variable keys?


var adddata = {};
adddata[ group ] = {};
adddata[ group ].type = type;
adddata[ group ].items = {};
adddata[ group ].items[ id ] = value;
$.extend( data, adddata );

Do i really need to define adddata this long way? If group and id are fixed strings, it's pretty short

$.extend( data, { group1:{ type: type, items:{ id1: value } } } );

Solution

  • Javascript only supports literal keys within object literals. You can only make the code a little shorter:

    var adddata = {};
    adddata[group] = { type: type, items: {} };
    adddata[group].items[id] = value;
    $.extend(data, adddata);