我有一个非常简单的对象,如下所示。我正在尝试使用var myArray = ["Monday", "Tuesday", "Wednesday"];
// forEach is built to only iterate the indexes of an array
// but allows us to do it without having to set up or maintain
// any counters.
myArray.forEach(function(value){
console.log(value);
});
,因为我在我的应用程序的其他部分使用它。我试图找到一种方法将特定键的值转换为数字。
在下面的示例中,类似于:
lodash
对象
_.mapValues(obj.RuleDetailID, _.method('parseInt'))
预期输出:
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"
}];
我是否可以与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"
}];
一起制作一系列方法来实现这一目标?
答案 0 :(得分:8)
如果您想 mutate 原始数组,请使用lodash#each
:
_.each(obj, item => item.RuleDetailID = parseInt(item.RuleDetailID, 10));
如果您想创建一个新数组(不要改变原始数组),请将lodash#map
与lodash#clone
一起使用:
let newArr = _.map(obj, item => {
let newItem = _.clone(item);
newItem.RuleDetailID = parseInt(newItem.RuleDetailID, 10);
return newItem;
});
答案 1 :(得分:0)
为使数组中对象的单个属性发生变异,我建议以下内容:
each
:https://lodash.com/docs/#forEach
update
:https://lodash.com/docs/#update
parseInt
:https://lodash.com/docs/#parseInt
RuleDetailID
属性更新为数字而不是字符串。repl.it上的示例:https://repl.it/repls/AdvancedOilyParentheses#index.js
示例:
_.each(arr, obj => _.update(obj, 'RuleDetailID', _.parseInt));
您使用了数据:(供参考:我将obj
重命名为arr
,因为它不是对象。)
var arr = [{
"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"
}];