简体   繁体   中英

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' } } ]
*/

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM