Multiple key names, same pair value

后端 未结 9 1724
萌比男神i
萌比男神i 2020-12-08 13:33

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 al

9条回答
  •  旧巷少年郎
    2020-12-08 14:02

    Now this may be overkill for you, but here's a generic function that will create an object with "multiple keys." What it actually does is have one real property with the actual value, and then defines getters and setters to forward operations from the virtual keys to the actual property.

    function multiKey(keyGroups) {
        let obj = {};
        let props = {};
    
        for (let keyGroup of keyGroups) {
            let masterKey = keyGroup[0];
            let prop = {
                configurable: true,
                enumerable: false,
    
                get() {
                    return obj[masterKey];
                },
    
                set(value) {
                    obj[masterKey] = value;
                }
            };
    
            obj[masterKey] = undefined;
            for (let i = 1; i < keyGroup.length; ++i) {
                if (keyGroup.hasOwnProperty(i)) {
                    props[keyGroup[i]] = prop;
                }
            }
        }
    
        return Object.defineProperties(obj, props);
    }
    

    This is less sketchy than you would expect, has basically no performance penalty once the object is created, and behaves nicely with enumeration (for...in loops) and membership testing (in operator). Here's some example usage:

    let test = multiKey([
        ['north', 'up'],
        ['south', 'down'],
        ['east', 'left'],
        ['west', 'right']
    ]);
    
    test.north = 42;
    test.down = 123;
    
    test.up; // returns 42
    test.south; // returns 123
    
    let count = 0;
    for (let key in test) {
        count += 1;
    }
    
    count === 4; // true; only unique (un-linked) properties are looped over
    

    Taken from my Gist, which you may fork.

提交回复
热议问题