问题描述
Underscore.js在集合上提供 _。每个
和 _。map
,这很不错,但我需要迭代我对象的所有属性。我需要修改值并保留键。例如。我有类似的东西: {a:1,b:2,c:3}
我需要执行一个更改值但保留键的操作。比方说,我会计算平方,我应该得到 {a:1,b:4,c:9}
。问题是:如何使用下划线(对vanilla javascript不感兴趣)?我喜欢这样的方法:
Underscore.js provides _.each
and _.map
on collections, which is nice, but I need to iterate over all attributes of my object. I need to modify the values and preserve the keys. E.g. I've got something like: {a:1, b:2, c:3}
and I need to perform an operation that changes the value but keeps the keys. Let's say, I'll calculate squares, I should get {a:1, b:4, c:9}
. The question is: how to do that using underscore (not interested in vanilla javascript)? I'd love a method like:
var a = {a:1, b:2, c:3}
_.magic(a, function(item){ return item*item; });
此外,如果有可能将其链接起来会很棒,因为我正在做地图,转储结果执行每个,然后再次使用地图(因为我需要)。
Additionally, it would be great if this was possible to chain it, since I'm doing a map, dump result to perform each and then use a map again (because I need to).
推荐答案
我看起来多一点进入我的一些片段,看看是否有一个选项可以改变原始对象,但我没有找到任何有趣的内容,所以我选择:\
I looked a little bit more into some of my snippets to see if there was an option to mutate the original object, but I didn't find anything interesting, so I'd go with this :\
var original = {a:1, b:2, c:3};
var squaredValues = _.object(_.map(original, function (value, key) {
return [key, value * value];
}));
我希望有一个更优雅的解决方案。
I'm hoping there's a more elegant solution though.
这篇关于迭代对象属性并修改它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!