Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
Sean Anderson Avatar asked Nov 07 '17 19:11

Sean Anderson


1 Answers

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>
like image 134
Ori Drori Avatar answered Oct 03 '22 10:10

Ori Drori