从具有多个副本的对象创建数组的最佳方法
从这样的对象:
{a:1, b: 2, c: 3}
我想变成
['a', 'b', 'b', 'c', 'c', 'c']
其中键是字符串,值是副本数,顺序并不重要。
最好的方法是什么?
我正在考虑使用 array.fill 但不确定这是否真的比迭代和推送更容易。
编辑:目前是这样:
const arr = []
_.each(obj, function (v, k) {
_.times(v, function () {
arr.push(k)
})
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以
object。条目
和填充
每个大小的数组。或与lodash
但是没有什么比简单的循环
You could
flatMap
theObject.entries
andfill
an array of each size.or with Lodash
But there's nothing like a simple loop
我将使用
Object.keys
将对象转换为键数组,然后使用新创建的空结果数组,然后映射键。对于每个键,我都会向现有结果添加一个填充数组。
这是 ES6 解决方案(不需要额外的库)
I would convert the object into an array of keys using
Object.keys
and then use a newly created empty results array, then map through the keys.For each key I would add a fill array to the existing results.
Here's the ES6 solution to that (no extra libraries required)
您可以使用
Object.entries
和Array#reduce
,如下所示:或者,使用 Array#push 代替 Array#concat,
或者,使用
for
循环,You can use
Object.entries
andArray#reduce
as follows:Or, using
Array#push
instead ofArray#concat
,Or, using
for
loops,