javascript lodash 将对象值(字符串)转换为数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46352462/
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
lodash convert object value(string) to number
提问by SBB
I have a very simple object like below. I am trying to use lodashas I am using it in other parts of my application. I am trying to find a way to convert the value of a specific key to a number.
我有一个非常简单的对象,如下所示。我正在尝试lodash在应用程序的其他部分使用它。我试图找到一种将特定键的值转换为数字的方法。
In the example below, something like:
在下面的示例中,类似于:
_.mapValues(obj.RuleDetailID, _.method('parseInt'))
Object:
目的:
var obj = [{
"RuleDetailID": "11624",
"AttributeValue": "172",
"Value": "Account Manager",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11626",
"AttributeValue": "686",
"Value": "Agent",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11625",
"AttributeValue": "180",
"Value": "Analyst",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11629",
"AttributeValue": "807",
"Value": "Individual Contributor",
"IsValueRetired": "0"
}, {
"RuleDetailID": "11627",
"AttributeValue": "690",
"Value": "Senior Agent",
"IsValueRetired": "0"
}];
Expected Output:
预期输出:
var obj = [{
"RuleDetailID": 11624,
"AttributeValue": "172",
"Value": "Account Manager",
"IsValueRetired": "0"
}, {
"RuleDetailID": 11626,
"AttributeValue": "686",
"Value": "Agent",
"IsValueRetired": "0"
}, {
"RuleDetailID": 11625,
"AttributeValue": "180",
"Value": "Analyst",
"IsValueRetired": "0"
}, {
"RuleDetailID": 11629,
"AttributeValue": "807",
"Value": "Individual Contributor",
"IsValueRetired": "0"
}, {
"RuleDetailID": 11627,
"AttributeValue": "690",
"Value": "Senior Agent",
"IsValueRetired": "0"
}];
Is there a chain of methods I can whip together with lodashto achieve this?
是否有一系列方法可以一起使用lodash来实现这一目标?
回答by alexmac
If you want to mutatethe original array, use lodash#each:
如果要改变原始数组,请使用lodash#each:
_.each(obj, item => item.RuleDetailID = parseInt(item.RuleDetailID, 10));
If you want to createa new array (don't mutate the original array), use lodash#mapwith lodash#clone:
如果要创建新数组(不要改变原始数组),请使用lodash#mapwith lodash#clone:
let newArr = _.map(obj, item => {
let newItem = _.clone(item);
newItem.RuleDetailID = parseInt(newItem.RuleDetailID, 10);
return newItem;
});

