0
var request = {
    headers: {
        "CONTENT-TYPE": "application/json",
        "accept": "application/json"
    }
};

目的是获取普通对象,但使用“规范化”键。如何将keysandvals与 Underscore 结合使用?

var normalize = function(h) { return h.toUpperCase(); },
    keys = _.map(_.keys(request.headers), normalize),
    vals = _.values(request.headers);

// Now combine (no obvious looping) keys and vals to obtain
// {
//     headers: {
//         "CONTENT-TYPE": "application/json",
//         "ACCEPT": "application/json"
//     }
// }
4

1 回答 1

3

你认为_.each是一个“明显的”循环结构吗?

var normalize = function(h) { return h.toUpperCase(); },
    normalizedHeaders = {};

_.each(request.headers, function(value, key) {
    normalizedHeaders[normalize(key)] = value;
});

如果您愿意,也可以通过减少来做到这一点:

var reducer = function(result, v, k) { result[normalize(k)] = v; return result; },
    normalizedHeaders = _.reduce(request.headers, reducer, {});

不过,无论哪种方式,幕后都会有一个循环。

于 2013-02-08T03:15:33.690 回答