Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return object from _.map()

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' } } ]
*/
like image 992
ThomasReggi Avatar asked Nov 14 '13 23:11

ThomasReggi


2 Answers

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.

like image 178
EmptyArsenal Avatar answered Sep 28 '22 08:09

EmptyArsenal


_.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;
}, {});
like image 32
Andrew Clark Avatar answered Sep 28 '22 09:09

Andrew Clark