ChristopherW ChristopherW - 5 months ago 13
Javascript Question

Multiple key names, same pair value

I'm trying to setup an object literal in a JavaScript script that has a key with multiple names. referring to the same object value i.e. something like these that I have already tried:

var holidays: {
"thanksgiving day", "thanksgiving", "t-day": {
someValue : "foo"
}
}

var holidays: {
["thanksgiving day", "thanksgiving", "t-day"]: {
someValue : "foo"
}
}


Is there a way I can accomplish this?

Answer

Another approach is to do some postprocessing

function expand(obj) {
    var keys = Object.keys(obj);
    for (var i = 0; i < keys.length; ++i) {
        var key = keys[i],
            subkeys = key.split(/,\s?/),
            target = obj[key];
        delete obj[key];
        subkeys.forEach(function(key) { obj[key] = target; })
    }
    return obj;
}

var holidays = expand({
    "thanksgiving day, thanksgiving, t-day": {
        someValue : "foo"
    } 
});