1

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.

2
  • Why do you need this and what exactly are you expecting? Please clear on your purpose. Commented Oct 28, 2020 at 7:04
  • @SajeebAhamed as I understand it, the rules do not allow for help to be specific to a single project, but wide spread enough that anyone with a simpilar problem can see what others have tried. Commented Oct 28, 2020 at 7:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution not sure why i didn't think about getters when I use them in classes all the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.