5

因此_.map(),下划线中的函数不会返回对象,而是需要它们。有没有办法让它返回它所需要的完全相同的对象?

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

4 回答 4

7

您可以使用_.object()将其变回对象。

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

至于直接使用_.map,您必须重写 map 才能做到这一点。

于 2013-11-14T23:15:36.343 回答
7

_.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;
}, {});
于 2013-11-14T23:17:58.227 回答
1

map返回一个array所以你没有办法让它返回原始对象而不写你自己的。请参阅文档

通过转换函数(迭代器)映射列表中的每个值来生成一个新的值数组。如果存在原生 map 方法,则会使用它。如果 list 是 JavaScript 对象,迭代器的参数将是 (value, key, list)。

于 2013-11-14T23:12:58.923 回答
1

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;
});
于 2013-11-14T23:16:15.453 回答