简体   繁体   中英

lodash - convert an object into a sorted array based on the keys of the object

I want to use lodash to convert an object like this:

var a = {1:'a', 3:'b', 2:'c'};

into a sorted array of values based on the keys of the object like:

var result = ['a','c','b'];

I know I can do this:

var keyRef = Object.keys(a).sort();
var result = keyRef.map(v => a[v]);

But is this way optimized - is there any function in lodash which is more optimized for this??

With plain Javascript, you could use Object.values and take this array as sorted result, because if the keys of the object could be read as 32 bit integer numbers, Javascript use them in numerical order.

Source:

 var object = { 1: 'a', 3: 'b', 2: 'c' }, values = Object.values(object); console.log(values); 

Using lodash,

 const o = {1:'a', 3:'b', 2:'c'}; const res = _.sortBy(o, (a, b) => b); console.log(res); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script> 

Lodash has the _.values(obj) function. However it is noted that the result ordering is not guaranteed. However, as @Nina pointed out, if you stick to ints as the keys, the ordering should be consistent (unless lodash is doing something weird).

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