lodash: mapping array to object

前端 未结 8 2249

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:41

    This is probably more verbose than you want, but you're asking for a slightly complex operation so actual code might be involved (the horror).

    My recommendation, with zipObject that's pretty logical:

    _.zipObject(_.map(params, 'name'), _.map(params, 'input'));
    

    Another option, more hacky, using fromPairs:

    _.fromPairs(_.map(params, function(val) { return [val['name'], val['input']));
    

    The anonymous function shows the hackiness -- I don't believe JS guarantees order of elements in object iteration, so callling .values() won't do.

提交回复
热议问题