问题描述
我想知道如何以更清洁和最佳的方式执行此操作:
I was wondering how to do this in the more cleaner and optimal way:
我有一个具有以下结构的对象:
I have an Object with the following structure:
{
"125": 2,
"439": 3,
"560": 1,
"999": 2,
...
}
我想创建一个平面数组,该数组重复每个键,其值指示该键的次数.以及将键(字符串)转换为整数的加分点.在此示例中,结果数组应为:
I want to create a flat array repeating every key, the number of times indicated by its value. And bonus points for converting keys (strings) to integers. In this example, the resulting array should be:
[ 125, 125, 439, 439, 439, 560, 999, 999 ]
我尝试了几种方法,但是它们看起来都过度设计.当然,有一种更简单的方法.这就是我用下划线得到的(它返回一个字符串数组,也不是整数):
I've tried several ways but they all look over-engineered. For sure there is an easier way.This is what I've got with underscore (and it returns an Array of strings, nor integers):
_.compact(_.flatten(_.map(files, function(num, id) {
return new Array(num+1).join('$'+id).split('$')
})))
我知道有很多方法可以做到这一点.我只想要一种干净快捷的方法.作为 Ruby 开发人员,它可能很容易:
I know there are plenty of ways to accomplish this. I just only want a clean and quick way. Being a Ruby developer it could be as easy as:
> files = {"125" => 2, "439" => 3, "560" => 1, "999" => 2}
=> {"125"=>2, "439"=>3, "560"=>1, "999"=>2}
> files.map {|key, value| [key.to_i] * value}.flatten
=> [125, 125, 439, 439, 439, 560, 999, 999]
谢谢.
推荐答案
尝试一下:
var obj = {
"125": 2,
"439": 3,
"560": 1,
"999": 2
}
var arr = [];
for (prop in obj) {
for (var i = 0; i < obj[prop]; i++)
arr.push(parseInt(prop));
}
console.log(arr)
这篇关于Javascript,重复对象键N次,其值为N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!