I have object with many keys, I want to get some of corresponding values into array, in certain order.
To get these values I can use deconstruction like
const obj = { foo: 1, bar: 3, baz: 2, other: 666, keys: "here" };
const { foo, bar, baz } = obj;
const array = [ foo, bar, baz ]; // 1, 3, 2
Of course, I can use many ways to achieve my goal, like without deconstruction:
const array = [ obj.foo, obj.bar, obj.baz ]; // 1, 3, 2
Or having these keys as an array and mapping over it.
const array = ["foo", "bar", "baz"].map( v => obj[v] )
But is there some simpler way?
In Perl, for example, is simple shortcut:
my %obj = (foo => 1, baz => 3, bar => 2);
my @arr = @obj{ ('foo','bar','baz') }; # 1, 3, 2
And instead ('foo','bar','baz')
here I can actually use any statement which returns list of these keys as selector for object (hash).
I can’t figure out something similar in JS.
2
Answers
There is the
with
statement but it is deprecatedhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with
Write your own util function like this or better:
For lazy folk 😁:
For who likes typing quotes and commas: