Ilja
Ilja

Reputation: 46479

Populate second array in an object with values from its first array

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.

Upvotes: 0

Views: 49

Answers (3)

fet
fet

Reputation: 624

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.

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

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);

Upvotes: 2

user3297291
user3297291

Reputation: 23372

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);

Upvotes: 0

Related Questions