Javascript, repeating an object key N-times, being N its value

后端 未结 6 1009
有刺的猬
有刺的猬 2020-12-20 01:11

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,
           


        
6条回答
  •  [愿得一人]
    2020-12-20 01:23

    Try this:

    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)

提交回复
热议问题