0

I have situation like this

const links = {
  ALLOWED1: [ 'some_path1' ],
  ALLOWED2: [ 'some_path2' ]
}

However I want to also allow paths from previous array on ALLOWED2, I've tried

const links = {
  ALLOWED1: [ 'some_path1' ],
  ALLOWED2: [ ...links['ALLOWED1'], 'some_path2' ]
}

But this is not valid as links will not defined yet. Of course I can populate it manually, but would rather find a more elegant solution.

4
  • ALLOWED2' should be ALLOWED2: Commented Dec 5, 2016 at 15:24
  • @KevinKloet thank you, fixed :) Commented Dec 5, 2016 at 15:25
  • How do you populate the object? Commented Dec 5, 2016 at 15:29
  • @AlexandruSeverin Manually, this is for routing, however I would like to find a solution to get strings from previous array and move them into next one, that wouldn't be manual. Commented Dec 5, 2016 at 15:31

3 Answers 3

2

You could do it with three lines instead

const links = {};
links.ALLOWED1 = [ 'some_path1' ];
links.ALLOWED2 = [ ...links['ALLOWED1'], 'some_path2' ];

console.log(links.ALLOWED2);

Remember, const only keeps the reference to the object constant, not the object's contents. For that you would need Object.defineProperty

If the contents of allowed1 and allowed2 ever change I might consider using a function to get them both. Like: links.all = () => [...links.ALLOWED1, ...links.ALLOWED2]. To me, that would read clearer in the code, unless it's really clear that allowed2 will always be a superset of allowed1.

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

1 Comment

Oops, thank you. Wish stackoverflow had a syntax checker :)
2

If you're not going to change ALLOWED2, you can convert it to a getter:

const links = {
  ALLOWED1: [ 'some_path1' ],
  get ALLOWED2() { return [ ...this['ALLOWED1'], 'some_path2' ] }
}

console.log(links.ALLOWED2);

Comments

0

An alternative, just because there are many ways to do this and it's mostly a matter of style :)

const links = (() => {
  const ALLOWED1 = ["some_path1"],
        ALLOWED2 = [...ALLOWED1, "some_path2"];
               
  return { ALLOWED1, ALLOWED2 };
})();

console.log(links);

Comments

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.