简体   繁体   中英

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?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM