0

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()?

3 Answers 3

2

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 });
Sign up to request clarification or add additional context in comments.

1 Comment

If I set _.double = double that would do it.
1

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; })
);

1 Comment

This was what I needed. See what I went went with below.
1

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; 
                }
        , {} )
};

2 Comments

context? Shouldn't it be func.call(context, value, key) then?
EDITED. I had to grab their source for that one. I copied the line of code they used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.