StackOverflow : Object creation

Create object with variable attribute names

by Hans PUFAL

HTML

<a href="http://stackoverflow.com/questions/10631007/how-to-use-a-variable-as-a-key-inside-object-initialiser">How to use a variable as a key inside object initialiser</a><br/>

JavaScript

function makeObj(a) {
    if (!(a instanceof Array)) throw ('Attempt to build object from ' + (typeof a));
    if (a.length % 2) throw ('Attempt to build object from an array length ' + a.length);

    for (var o = {}, i = a.length - 1; i > 0; i -= 2)
        o[a[i - 1]] = a[i];
    return o;
}

var thisName = 'Hans PUFAL';
var thisValue = 'Paleoinformaticien';
var session_id = '123edrft456fg';

var o = makeObj(['p_session_id', session_id,
                 'p_username',   'HBP',
                 thisName,       thisValue]);

document.write(JSON.stringify(o));