Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take an array and make an object out of flipped indices/values

Is there a more straightforward way in lodash to achieve the following,

var o = _.reduce([2, 3, 7], function(acc, v, i) {
    acc[v] = i || "0";
    return acc;
}, {});

Result,

Object {2: "0", 3: 1, 7: 2}
like image 587
mpapec Avatar asked Mar 13 '23 00:03

mpapec


1 Answers

Try to use .reduce() with a starting value of an empty object,

var obj = [2, 3, 7].reduce(function(a,b,i){
  return (a[b] = i, a);
}, {});

If you want it to be shorter even more then use E6 version,

var obj = [2, 3, 7].reduce((a,b,i) => (a[b] = i, a), {});
like image 85
Rajaprabhu Aravindasamy Avatar answered May 01 '23 16:05

Rajaprabhu Aravindasamy