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

后端 未结 6 1005
有刺的猬
有刺的猬 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:19

    Whether any of these approaches is cleaner is quite subjective:

    // some helper function for creating an array with repeated values
    function repeat(val, times) {
        var arr = [];
        for(var i = 0; i < times; i = arr.push(val));
        return arr;
    }
    
    function convert(obj) {
        var result = [], key;
        for(key in obj) {
            result = result.concat(repeat(+key, obj[key]));
        }
        return result;
    }
    

    Or a more functional approach:

    Object.keys(obj).reduce(function(result, key) {
        return result.concat(repeat(+key, obj[key]));
    }, []);
    
    // with underscore.js
    _.reduce(_.keys(obj), function(result, key) {
        return result.concat(repeat(+key, obj[key]));
    }, []);
    

提交回复
热议问题