Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash convert object value(string) to number

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?

like image 319
SBB Avatar asked Dec 18 '22 04:12

SBB


1 Answers

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;
});
like image 147
alexmac Avatar answered Dec 24 '22 00:12

alexmac