skip to Main Content

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


  1. There is the with statement but it is deprecated

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with

    const obj = { foo: 1, bar: 3, baz: 2, other: 666, keys: "here" }
    with(obj) {
      const arr = [foo, bar, baz]
      console.log(arr)
    }
    Login or Signup to reply.
  2. Write your own util function like this or better:

    For lazy folk 😁:

    const obj = { foo: 1, bar: 3, baz: 2, other: 666, keys: "here" };
    const obj2arr = (obj, fields) => fields.match(/S+/g).map(field => obj[field]);
    
    const arr = obj2arr(obj, 'foo bar baz');
    console.log(...arr);

    For who likes typing quotes and commas:

    const obj = { foo: 1, bar: 3, baz: 2, other: 666, keys: "here" };
    const obj2arr = (obj, ...fields) => fields.map(field => obj[field]);
    
    const arr = obj2arr(obj, 'foo', 'bar', 'baz');
    console.log(...arr);
    Cycles: 1000000 / Chrome/117
    -------------------------------------------------------
    rest arguments    25/min  1.0x   29   25   29   33   32
    regex            132/min  5.3x  135  132  147  142  146
    -------------------------------------------------------
    https://github.com/silentmantra/benchmark
    
    <script benchmark="1000000">
    const obj = { foo: 1, bar: 3, baz: 2, other: 666, keys: "here" };
    
    // @benchmark regex
    const regex = /S+/g;
    const obj2arr = (obj, fields) => fields.match(regex).map(field => obj[field]);
    // @run
    obj2arr(obj, 'foo bar baz');
    
    // @benchmark rest arguments
    
    const obj2arr2 = (obj, ...fields) => fields.map(field => obj[field]);
    // @run
    obj2arr2(obj, 'foo', 'bar', 'baz');
    
    </script>
    <script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search