var request = {
headers: {
"CONTENT-TYPE": "application/json",
"accept": "application/json"
}
};
目的是获取普通对象,但使用“规范化”键。如何将keys
和vals
与下划线结合使用?
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"
// }
// }
答案 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, {});
无论如何,无论如何都会有一个循环。