Convert JavaScript array of 2 element arrays into object key value pairs

后端 未结 5 863
陌清茗
陌清茗 2020-11-29 10:58

What is the fastest algorithm for getting from something like this:

var array = [ [1,\'a\'], [2,\'b\'], [3,\'c\'] ];

to something like this

相关标签:
5条回答
  • 2020-11-29 11:32

    Lodash has a _.fromPairs method that does exactly that.

    From the documentation:
    _.fromPairs([['a', 1], ['b', 2]]); // => { 'a': 1, 'b': 2 }

    0 讨论(0)
  • 2020-11-29 11:33

    Terse version using modern syntax:

    let objectify = a => a.reduce( (o,[k,v]) => (o[k]=v,o), {} );
    

    I use this technique as part of a terse query string parser:

    // Converts "?foo=bar&j=1&go" into { foo:'bar', j:'1', go:true }
    function parseQueryString(qs) {
        var q = decodeURIComponent;
        return qs.replace(/^\?/,'').split('&').map(s => s.split('='))
                 .reduce((o,[k,v]) => (o[q(k)] = v?q(v):true, o), {});
    }
    
    0 讨论(0)
  • 2020-11-29 11:37

    You can wrap the entire thing within Array.prototype.reduce, like this

    function objectify(array) {
        return array.reduce(function(result, currentArray) {
            result[currentArray[0]] = currentArray[1];
            return result;
        }, {});
    }
    
    console.log(objectify([ [1, 'a'], [2, 'b'], [3, 'c'] ]));
    # { '1': 'a', '2': 'b', '3': 'c' }
    

    We are just accumulating the key-value pairs in the result object and finally the result of reduce will be the result object and we are returning it as the actual result.

    0 讨论(0)
  • 2020-11-29 11:50

    With Object.fromEntries, you can convert from Array to Object:

    var array = [
      [1, 'a'],
      [2, 'b'],
      [3, 'c']
    ];
    var object = Object.fromEntries(array);
    console.log(object);

    0 讨论(0)
  • 2020-11-29 11:51

    You could indeed use Array.prototype.reduce:

    function objectify(array) {
        return array.reduce(function(p, c) {
             p[c[0]] = c[1];
             return p;
        }, {});
    }
    

    where p is the result of the previous iteration, initially {}, and c is the current element of the array.

    It's unlikely to be any faster than array.forEach, but it is IMHO cleaner. I don't believe there's any simpler implementation than this.

    NB: a function to do exactly this already exists in the Underscore library: _.object(array)

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