如何在不使用Underscore循环的情况下组合键和值?

时间:2013-02-08 03:08:01

标签: javascript underscore.js

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

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

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"
//     }
// }

1 个答案:

答案 0 :(得分: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, {});

无论如何,无论如何都会有一个循环。