How to produce an array from an object where the number of elements is determined by Object.values?

后端 未结 7 531
感情败类
感情败类 2020-12-22 05:15

I have an object like so:

{ green: 2, blue: 1, red: 2}

How can I turn it into an array that looks like this:

[ \'green\', \         


        
相关标签:
7条回答
  • 2020-12-22 05:36
    var data={ green: 2, blue: 1, red: 2};
    var newData=[];
    for(let i in data){
        for(let j=0;j<data[i];j++){
            newData.push(i);
        }
    }
    console.log('newData = ', newData);
    

    output

    newData = ["green", "green", "blue", "red", "red"]
    

     

    0 讨论(0)
提交回复
热议问题