I have a very simple object like below. I am trying to use lodash
as 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.
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 lodash
to achieve this?
If you want to mutate the original array, use lodash#each
:
_.each(obj, item => item.RuleDetailID = parseInt(item.RuleDetailID, 10));
If you want to create a new array (don't mutate the original array), use lodash#map
with lodash#clone
:
let newArr = _.map(obj, item => {
let newItem = _.clone(item);
newItem.RuleDetailID = parseInt(newItem.RuleDetailID, 10);
return newItem;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With