Underscore.js:使用对象中的键创建对象列表中的地图 [英] Underscore.js: create a map out of list of objects using a key found in the object
问题描述
我正在使用优秀的 Underscore.js 库。我有一个特定的任务,我可以使用JavaScript或jQuery做得很好但是想知道在Underscore中是否有某种抽象可以让我错过了。
I am using the excellent Underscore.js library. I have a specific task which I can do fine using JavaScript or jQuery but was wondering if there was some sort of abstraction avaialable in Underscore that I was missing out on.
基本上我有一个像这样的对象 -
Essentially I have an object like so -
var some_object_array = [{id: "a", val: 55}, {id: "b", val: 1}, {id: "c", val: 45}];
我想将其转换为 -
I want to convert this into -
var some_map = {"a": {id: "a", val: 55}, "b": {id: "b", val: 1}, "c": {id: "c", val: 45}};
我知道我可以使用 _。groupBy(some_object_array,id )
。但是这会返回一个这样的地图 -
I know that I can use _.groupBy(some_object_array, "id")
. But this returns a map like so -
var some_grouped_map = {"a": [{id: "a", val: 55}], "b": [{id: "b", val: 1}], "c": [{id: "c", val: 45}]};
请注意,这样做会做广告宣传。但是我希望得到 some_map
,而不是自己迭代对象。
Note that this does what it is advertised to do. But I was hoping to get some_map
without iterating over the objects myself.
任何帮助表示赞赏。
推荐答案
FWIW因为undercore.js你现在可以使用 _.object()
FWIW since underscore.js you can now use _.object()
var some_map = _.object(_.map(some_object_array, function(item) {
return [item.id, item]
}));
这篇关于Underscore.js:使用对象中的键创建对象列表中的地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!