redolent
redolent

Reputation: 4259

Underscore.js perform operation on an object, not an array

Hey I'm new to underscore.js and I'm trying to figure out how to perform an operation on a map. I read through the API and I'm afraid I'm missing something.

Here's what I'd like to do:

doubled = _.someFunction( { bob: 25, sally: 30, tom: 5 }
                          , function(value){ return value*2; } 
                        );

Returning:

{ bob: 50, sally: 60, tom: 10 }

Any idea how to do this? Should I create a new function with _.mixin()?

Upvotes: 0

Views: 426

Answers (3)

redolent
redolent

Reputation: 4259

For those interested, here's what I ended up doing: (See the reduce function API)

_.mapValues = function( object, iterator, context ){
    if (context) iterator = _.bind(iterator, context);
    return _.reduce( 
          object
        , function( memo, value, key ){ 
                memo[key] = iterator( value, key ); 
                return memo; 
                }
        , {} )
};

Upvotes: 1

Bergi
Bergi

Reputation: 664444

No, Underscore indeed does not provide a map function for objects. (You can use _.map on objects, but it will return an array)

So, you will have to do it manually:

_.someFunction = function(o, f) {
    var res = {};
    for (var p in o)
        res[p] = f(o[p]);
    return res;
};

Of course you might use some iteration functions from underscore. Without a helper function, these snippets might be more or less expressive:

var doubled = {};
_.each({ bob: 25, sally: 30, tom: 5 }, function(p, value){
    doubled[p] = value*2;
});
var doubled = _.reduce({ bob: 25, sally: 30, tom: 5 }, function(m, value, p){
    m[p] = value*2;
    return m;
}, {});
var obj = { bob: 25, sally: 30, tom: 5 };
var doubled = _.object(
  _.keys(obj),
  _.map(_.values(obj), function(value){ return value*2; })
);

Upvotes: 1

Nico Valencia
Nico Valencia

Reputation: 141

You could make a double function like this:

function double(data) {

  var doubled = {};

  _.each(data, function(value, key) {
    doubled[key] = 2 * value;
  });

  return doubled;

};

double({ bob: 25, sally: 30, tom: 5 });

Upvotes: 2

Related Questions