Multiple key names, same pair value

后端 未结 9 1740
萌比男神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:22

    JSON does not offer such a feature, nor do Javascript object literals.

    You might be able to make do with something like this:

    holidays = {
        thanksgiving: {foo: 'foo'},
        groundhogDay: {foo: 'bar'},
        aliases: {
            'thanksgiving day': 'thanksgiving',
            't-day': 'thanksgiving',
            'Bill Murrays nightmare': 'groundhogDay'
        }
    }
    

    and then you can check

    holidays[name] || holidays[holidays.aliases[name]]
    

    for your data.

    It's not a wonderful solution. But it wouldn't be too difficult to write a little function that created this sort of object out of a representation like:

    [
        {
            names: ['thanksgiving', 'thanksgiving day', 't-day'],
            obj: {foo: 'foo'}
        },
        {
            names: ['groundhogDay', 'Bill Murrays nightmare'],
            obj: {foo: 'bar'}
        },
    ]
    

    if that would be easier to maintain.

提交回复
热议问题