在 Javascript 中,字典理解,或对象`map`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11068247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Javascript a dictionary comprehension, or an Object `map`
提问by Cuadue
I need to generate a couple of objects from lists in Javascript. In Python, I'd write this:
我需要从 Javascript 中的列表生成几个对象。在 Python 中,我会这样写:
{key_maker(x): val_maker(x) for x in a_list}
Another way to ask is does there exist something like jQuery.map()
which aggregates objects? Here's my guess (doesn't work):
另一种提问方式是是否存在jQuery.map()
聚合对象之类的东西?这是我的猜测(不起作用):
var result = {}
$.map(a_list, function(x) {
$.extend(result, {key_maker(x): val_maker(x)})
})
采纳答案by Cuadue
Assuming a_list
is an Array, the closest would probably be to use .reduce()
.
假设a_list
是一个数组,最接近的可能是使用.reduce()
.
var result = a_list.reduce(function(obj, x) {
obj[key_maker(x)] = val_maker(x);
return obj;
}, {});
Array comprehensions are likely coming in a future version of JavaScript.
数组推导式可能会出现在 JavaScript 的未来版本中。
You can patch non ES5 compliant implementations with the compatibility patch from MDN.
您可以使用MDN 中的兼容性补丁修补非 ES5 兼容的实现。
If a_list
is not an Array, but a plain object, you can use Object.keys()
to perform the same operation.
如果a_list
不是数组,而是普通对象,则可以使用它Object.keys()
来执行相同的操作。
var result = Object.keys(a_list).reduce(function(obj, x) {
obj[key_maker(a_list[x])] = val_maker(a_list[x]);
return obj;
}, {});
回答by fizzyh2o
Here's a version that doesn't use reduce:
这是一个不使用reduce的版本:
Object.fromEntries( a_list.map( x => [key_maker(x), value_maker(x)]) );
Object.fromEntriesis basically the same as _.fromPairsin Lodash. This feels the most like the Python dict comprehension to me.
Object.fromEntries与Lodash中的 _.fromPairs基本相同。这对我来说最像 Python dict 理解。
回答by benwixen
Old question, but the answer has changed slightly in new versions of Javascript. With ES2015 (ES6) you can achieve a one-liner object comprehension like this:
老问题,但答案在新版本的 Javascript 中略有变化。使用 ES2015 (ES6),您可以实现这样的单行对象理解:
a_list.reduce((obj, x) => Object.assign(obj, { [key_maker(x)]: value_maker(x) }), {})
回答by Steven Almeroth
ES5introduced Map
for an OrderedDict. A Map comprehension might look like:
ES5Map
为OrderedDict引入。地图理解可能如下所示:
Map( Array.map(function(o){return[ key_maker(o), val_maker(o) ]}))
Example:
例子:
> a_list = [ {x:1}, {x:2}, {x:3} ]
< [ Object, Object, Object ]
>
> let dict = new Map(a_list.map(function(o){return[ o.x, o.x**2 ]}))
< Map[3]
< 0 : {1 => 1}
< 1 : {2 => 4}
< 2 : {3 => 9}
>
> dict.get(2)
< 4
回答by Elias Zamaria
回答by smartexpert
A shorter ES6 version would be:
较短的 ES6 版本将是:
a_list.reduce((obj, x) => (key_maker(obj[x]) = val_maker(x), obj),{})