简体   繁体   中英

JSON use multiple keys for the same value in an object

I am trying to use a JSON object that holds data in a similar fashion to

const obj = {
    key_a : [1, 2, 3, 4, 5],
    key_b : [2, 8, 4, 0, 9, 5],
    key_c : [1, 2, 3, 4, 5]
}

as you can see key_a and key_c have the same data.

Idealy I would have something like

const obj = {
    [key_a, key_c] : [1, 2, 3, 4, 5]
}

or

const obj = {
    key_a : [1, 2, 3, 4, 5]
    key_c : key_a
}

but offcourse these do not work.

Is there a way to "without merging" make the JSON object more DRY

my Solution at the moment is to use a variable that takes the key and uses a single key as such

input = (input === key_a || input === key_c) ? key_ac : input;
const obj = {
    key_ac : [1, 2, 3, 4, 5],
    key_b : [2, 8, 4, 0, 9, 5]
}

This feel clumsy and also like there should be a better solution. It also requires changing the key names, which I would also like to avoid.

You can use getter method for this,

const obj = {
    key_a : [1, 2, 3, 4, 5],
    key_b : [2, 8, 4, 0, 9, 5],
    get key_c() { return this.key_a; }
}

Now if you console.log obj.key_c you will get the value of obj.key_a . So, now if you update key_a you don't have to update key_c as it is a getter. Whenever you try to get obj.key_c it will give you the latest obj.key_a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM