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

Question

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

Answers 1
Added at 2017-11-07 20:11
Tags
Question

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?

Answers to

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

nr: #1 dodano: 2017-11-07 20:11

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>

Source Show
◀ Wstecz