lodash: mapping array to object

前端 未结 8 2233

Is there a built-in lodash function to take this:

var params = [
    { name: \'foo\', input: \'bar\' },
    { name: \'baz\', input: \'zle\' }
];
相关标签:
8条回答
  • 2020-12-23 14:59

    You should be using _.keyBy to easily convert an array to an object.

    Docs here

    Example usage below:

    var params = [
        { name: 'foo', input: 'bar' },
        { name: 'baz', input: 'zle' }
    ];
    console.log(_.keyBy(params, 'name'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    If required, you can manipulate the array before using _.keyBy or the object after using _.keyBy to get the exact desired result.

    0 讨论(0)
  • 2020-12-23 15:04

    Yep it is here, using _.reduce

    var params = [
        { name: 'foo', input: 'bar' },
        { name: 'baz', input: 'zle' }
    ];
    
    _.reduce(params , function(obj,param) {
     obj[param.name] = param.input
     return obj;
    }, {});
    
    0 讨论(0)
提交回复
热议问题