Lodash如何将对象转换为排序数组 [英] How to transform object into sorted array by Lodash

查看:124
本文介绍了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'})

这是

9.1.12 [[OwnPropertyKeys]]()

9.1.12 [[OwnPropertyKeys]] ( )

当O的[[OwnPropertyKeys]]内部方法称为 采取以下步骤:

When the [[OwnPropertyKeys]] internal method of O is called the following steps are taken:

  1. 让键成为一个新的空列表.

  1. Let keys be a new empty List.

对于每个人 O的属性键P,它是整数索引,以递增数字表示 索引顺序

For each own property key P of O that is an integer index, in ascending numeric index order

2a.将P添加为键的最后一个元素.

2a. Add P as the last element of keys.

这篇关于Lodash如何将对象转换为排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆