javascript 使用 lodash 将所有对象值转换为小写
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33809686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert all object values to lowercase with lodash
提问by Jesus_Maria
I have an object:
我有一个对象:
z = {x: 'HHjjhjhHHHhjh', y: 'YYYYY', c: 'ssss'}
I need to convert all values to lowercase
我需要将所有值转换为小写
z = {x: 'hhjjhjhhhhhjh', y: 'yyyyy', c: 'ssss'}
How to do this in one time, maybe with lodash? for now I am doing:
如何一次性做到这一点,也许使用 lodash?现在我正在做:
z.x = z.x.toLowerCase()
z.y = z.y.toLowerCase()
z.c = z.c.toLowerCase()
回答by Adam Boduch
Using lodash, you can call mapValues()to map the object values, and you can use method()to create the iteratee:
使用 lodash,您可以调用mapValues()来映射对象值,并且您可以使用method()创建迭代对象:
_.mapValues(z, _.method('toLowerCase'));
回答by Molomby
A lot of the stuff you'd use Lodash for you can do quite easily in ES6/ES2015. Eg, in this case you could:
很多你使用 Lodash 的东西都可以在 ES6/ES2015 中轻松完成。例如,在这种情况下,您可以:
var z = { x: 'HHjjhjhHHHhjh', y: 'YYYYY', c: 'ssss' };
var y = Object.keys(z).reduce((n, k) => (n[k] = z[k].toLowerCase(), n), {});
console.log(y);
// { x: 'hhjjhjhhhhhjh', y: 'yyyyy', c: 'ssss' }
Pretty neat, eh?
很整洁,嗯?
回答by Rick Hitchcock
回答by Shilly
In vanilla js:
在香草js中:
Object.keys(z).forEach(function ( key ) {
z[key] = z[key].toLowerCase();
});
Lodash might have shorter forEach syntax.
Lodash 可能有更短的 forEach 语法。
回答by nils
If you want a solution without lodash, you could use Object.keysand Array.prototype.reduce:
如果你想要一个没有 lodash 的解决方案,你可以使用Object.keys和Array.prototype.reduce:
var z = {x: 'HHjjhjhHHHhjh', y: 'YYYYY', c: 'ssss'};
var lowerZ = Object.keys(z).reduce(function(obj, currentKey) {
obj[currentKey] = z[currentKey].toLowerCase();
return obj;
}, {});
回答by Tomasz Jakub Rup
CoffeeScript solution:
CoffeeScript 解决方案:
z = x: 'HHjjhjhHHHhjh', y: 'YYYYY', c: 'ssss'
for key, val of z
z[key] = val.toLowerCase()