Monday, May 20, 2024
18
rated 0 times [  24] [ 6]  / answers: 1 / hits: 71296  / 10 Years ago, wed, september 24, 2014, 12:00:00

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).


More From » underscore.js

 Answers
27

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.


[#69354] Sunday, September 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emanir

Total Points: 151
Total Questions: 90
Total Answers: 105

Location: Suriname
Member since Sun, Jun 13, 2021
3 Years ago
;