Lodash如何将对象转换为排序数组 [英] How to transform object into sorted array by Lodash
本文介绍了Lodash如何将对象转换为排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何通过lodash将{2:'b',3:'c',1:'a'}
转换为[{1:'a'},{2:'b'},{3:'c'}]
?
How to transform {2:'b',3:'c',1:'a'}
into [{1:'a'},{2:'b'},{3:'c'}]
by lodash?
推荐答案
使用Object.keys
+ Array.map
相当简单,您真的不需要lodash:
It's fairly trivial using Object.keys
+ Array.map
, you really don't need lodash:
const obj = {2:'b',3:'c',1:'a'};
const arr = Object.keys(obj).map(key => ({ [key]: obj[key] }))
console.log(arr)
关于缺少sort
函数的问题,以上代码利用了这样一个事实,即按索引(按规范)顺序存储数字索引的对象键.亲自检查订单:
Regarding the lack of a sort
function, the above code is exploiting the fact that numerically indexed Object keys are (per the spec) stored sequentially. Check the order for yourself:
console.log({2:'b',3:'c',1:'a'})
查看全文