Javascript下划线数组到对象

Javascript underscore array to object

本文关键字:对象 数组 下划线 Javascript      更新时间:2023-09-26

有没有一种简单/干净的方法使用Undercore来打开这个

[ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ]

进入

 { 'low'    : 9,
   'medium' : 7,
   'high'   : 5 }

您可以考虑_.indexBy(…(

var data = [{
    id: 1,
    name: 'Jon Doe',
    birthdate: '1/1/1991',
    height: '5 11'
}, {
    id: 2,
    name: 'Jane Smith',
    birthdate: '1/1/1981',
    height: '5 6'
}, {
    id: 3,
    name: 'Rockin Joe',
    birthdate: '4/4/1994',
    height: '6 1'
}, {
    id: 4,
    name: 'Jane Blane',
    birthdate: '1/1/1971',
    height: '5 9'
}, ];
var transformed = _.indexBy(data, 'id');

这是一把小提琴:https://jsfiddle.net/4vyLtcrf/3/

更新:在Lodash 4.0.1中,方法_.indexBy已重命名为_.keyBy

var data = [ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ];

你可以用_.map_.values_.object来完成,就像这个一样

console.log(_.object(_.map(data, _.values)));
# { medium: 7, low: 9, high: 5 }

解释

我们使用map函数将values函数(它获得给定对象的所有值(应用于data的所有元素,这将给出

# [ [ 'medium', 7 ], [ 'low', 9 ], [ 'high', 5 ] ]

然后我们使用object函数将其转换为一个对象。

下面是香草js:

var result = {};
[ { id: 'medium', votes: 7 },
  { id: 'low',    votes: 9 },
  { id: 'high',   votes: 5 } ].forEach(function(obj) {
    result[obj.id] = obj.votes;
});
console.log(result);

使用我更简单:each:

   var t = {};
   _.each(x, function(e){
     t[e.id] = e.votes;
   });
//--> {medium: 7, low: 9, high: 5}

下划线最有力的方法是reduce。你几乎可以用它做任何事情。更大的好处是你只需迭代一次集合!

var array = [ 
    { id: 'medium', votes: 7 },
    { id: 'low',    votes: 9 },
    { id: 'high',   votes: 5 } 
];
var object = _.reduce(array, function(_object, item) { 
    _object[item.id] = item.votes; 
    return _object; 
}, {});

运行后,对象将是:

{
  medium:7,
  low:9,
  high:5
}

使用indexBy

_.indexBy([ 
   { id: 'medium', votes: 7 },
   { id: 'low',    votes: 9 },
   { id: 'high',   votes: 5 } 
 ], 'id');

我知道这是一篇旧文章,但您可以使用_.reduce以一种干净的方式进行转换

var data = [
    { id: 'medium', votes: 7 },
    { id: 'low',    votes: 9 },
    { id: 'high',   votes: 5 }
]
var output = _.reduce(data, function(memo, entry) {
    memo[entry.id] = entry.votes;
    return memo;
}, {});
console.log(output);

您可以使用本机JS Array.reduce

const myArray = [ { id: 'medium', votes: 7 },
{ id: 'low',    votes: 9 },
{ id: 'high',   votes: 5 } ]
const myObject = myArray.reduce((obj, item)=>{
  o[item.id] = item.votes
  return o
}, {})

有关更多详细信息,请查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce