Return object from _.map()

25,579

Solution 1

You can use _.object() to turn it back into an object.

var regurgitate_cars = _.object(
    _.map(cars, function(value, key){
        return [key, value];
    })
);

As for doing that directly with _.map, you'd have to rewrite map to do it.

Solution 2

_.map() will always return an array, but you can get the behavior with _.reduce():

var regurgitateCars = _.reduce(cars, function(memo, value, key) {
    memo[key] = value;
    return memo;
}, cars);

Note that this will modify and return the original object, if you wanted a copy you can provide an empty object as the third argument, which will be used as the memo argument on the first call of the anonymous function:

var regurgitateCars = _.reduce(cars, function(memo, value, key) {
    memo[key] = value;
    return memo;
}, {});

Solution 3

map returns an array so there's no way you could get it to return the original object with out writing your own. See documentation:

Produces a new array of values by mapping each value in list through a transformation function (iterator). If the native map method exists, it will be used instead. If list is a JavaScript object, iterator's arguments will be (value, key, list).

Solution 4

There is no way to return a object with the current implementation of map. It's been suggested that the library add a .mapValues() function which would do what you like. Here's how you would add it to your code:

_.mixin({
    mapValues: function (input, mapper) {
        return _.reduce(input, function (obj, v, k) {
            obj[k] = mapper(v, k, input);
        }, {});
    }
});

Now you can use mapValues to return a new object:

var regurgitate_cars = _.mapValues(cars, function(value, key){
    return value;
});
Share:
25,579
ThomasReggi
Author by

ThomasReggi

Updated on July 09, 2022

Comments

  • ThomasReggi
    ThomasReggi almost 2 years

    So the _.map() function in underscore doesn't return an object, but it takes them. Is there any way for it to return the exact same object it takes?

    var _ = require("underscore");
    
    var cars = {
        "mom": {
            "miles": "6",
            "gas": "4"
        },
        "dad": {
            "miles": "6",
            "gas": "4"
        }
    }
    
    var regurgitate_cars = _.map(cars, function(value, key){
        return value;
    });
    
    /*
    [ { miles: '6', gas: '4' }, { miles: '6', gas: '4' } ]
    */
    
    var regurgitate_cars = _.map(cars, function(value, key){
        var transfer = {};
        transfer[key] = value;
        return transfer;
    });
    
    /*
    [ { mom: { miles: '6', gas: '4' } },
      { dad: { miles: '6', gas: '4' } } ]
    */
    
  • McGarnagle
    McGarnagle over 10 years
    You would need to return [key, value] for this to work ...?
  • EmptyArsenal
    EmptyArsenal over 10 years
    @McGarnagle, good call. You are right, and the post has been updated. And it looks much more succinct.