Search code examples
javascriptfunctional-programminglodash

Lodash: Pick list of values from object into array with guaranteed order


I have an object which looks like:

const myObject = {
   foo: '000',
   bar: '123',
   baz: '456'
};

I would like to put a subset of myObject's property values into an array. I need to preserve ordering.

A manual solution would look like:

const values = [myObject.foo, myObject.baz];

One attempt might look like:

const values = _.values(_.pick(myObject, ['foo', 'baz']));

This solution isn't correct because pick creates a new object. Calling _.values on the new object removes the ordering specified in the picked array.

Is there a simple way of going about doing this?


Solution

  • You can use _.at() in a similar way to _.pick() to get an array:

    const myObject = {
       foo: '000',
       bar: '123',
       baz: '456'
    };
    
    const array = _.at(myObject, ['foo', 'bar', 'baz']);
    
    console.log(array);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    Or you can use Array#map in vanilla JS:

    const myObject = {
       foo: '000',
       bar: '123',
       baz: '456'
    };
    
    const array = ['foo', 'bar', 'baz'].map((key) => myObject[key]);
    
    console.log(array);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>