使用Underscore有没有一种简单/清晰的方法可以将此内容转换为
[ { id: 'medium', votes: 7 },
{ id: 'low', votes: 9 },
{ id: 'high', votes: 5 } ]
进入
{ 'low' : 9,
'medium' : 7,
'high' : 5 }
使用Underscore有没有一种简单/清晰的方法可以将此内容转换为
[ { 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
函数将其转换为对象。
data
的定义。有一个换行符。我刚刚把它删除了。 - thefourtheye这里是使用原生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}
Underscore中最强大的方法是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
}
我知道这是一个旧帖子,但你可以使用_.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
_.indexBy([
{ id: 'medium', votes: 7 },
{ id: 'low', votes: 9 },
{ id: 'high', votes: 5 }
], 'id');
id
属性,但在大多数情况下这应该是可以接受的(在其他情况下也很容易进行后排除)。 - peterp_.groupBy()
提供了类似的解决方案。 - Hartley Brody