The*_*igC 15 javascript arrays object underscore.js
是否有一种简单/干净的方式使用Underscore来解决这个问题
[ { id: 'medium', votes: 7 },
{ id: 'low', votes: 9 },
{ id: 'high', votes: 5 } ]
Run Code Online (Sandbox Code Playgroud)
成
{ 'low' : 9,
'medium' : 7,
'high' : 5 }
Run Code Online (Sandbox Code Playgroud)
kro*_*olk 43
你可以考虑_.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');
Run Code Online (Sandbox Code Playgroud)
这是一个小提琴:https: //jsfiddle.net/4vyLtcrf/3/
更新:在Lodash 4.0.1中,方法_.indexBy已重命名为_.keyBy
the*_*eye 17
var data = [ { id: 'medium', votes: 7 },
{ id: 'low', votes: 9 },
{ id: 'high', votes: 5 } ];
Run Code Online (Sandbox Code Playgroud)
你可以这样做_.map,_.values并且_.object像这样
console.log(_.object(_.map(data, _.values)));
# { medium: 7, low: 9, high: 5 }
Run Code Online (Sandbox Code Playgroud)
说明
我们使用map函数将values函数(它获取给定对象的所有值)应用于所有元素data,这将给出
# [ [ 'medium', 7 ], [ 'low', 9 ], [ 'high', 5 ] ]
Run Code Online (Sandbox Code Playgroud)
然后我们使用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);
Run Code Online (Sandbox Code Playgroud)