Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over object attributes and modify them

Tags:

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

like image 221
ducin Avatar asked Sep 24 '14 09:09

ducin


People also ask

How do you iterate over an object in Python?

Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, and sets. The iterator object is initialized using the iter() method. It uses the next() method for iteration. next ( __next__ in Python 3) The next method returns the next value for the iterable.

How do you iterate keys in an object?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.


1 Answers

_.mapObject (added in version 1.8) is exactly what you're looking for.


For previous versions, can mutate the original object using the third argument to the _.each callback.

_.each({a:1, b:2, c:3}, function(value, key, obj) { obj[key] = value * value; }); 

Using _.reduce with an initial memo can create a brand new object as well.

_.reduce({a:1, b:2, c:3}, function(memo, value, key) {     memo[key] = value * value;     return memo; }, {}); 

I'd prefer the _.reduce approach. A simple mixin will make it behave exactly like _.map.

_.mixin({     magic: function(obj, iterator, context) {         return _.reduce(obj, function(memo, value, key) {             memo[key] = iterator.call(context, value, key, obj);             return memo;         }, {});     } }); 
like image 117
Justin Avatar answered Sep 23 '22 12:09

Justin