Lets say I have an object
var users = [
  { Mike:    'true' },
  { Tony:    'True' },
  { Ismael:  'RU' }
];
I have this problem where I want to normalise my object, basically replace "true" or "True" with a boolean true anything else should be false. 
By the way I may have the syntax for users wrong, chrome is telling me users.constructor == Object and not Array.
How can I achieve this using lodash?
Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. The _. replace() method replace the matches for pattern in string with replacement. This method is based on String#replace.
The Lodash _. unset() method is used to remove the property at the path of the object. If the property is removed then it returns True value otherwise, it returns False.
To remove a null from an object with lodash, you can use the omitBy() function. If you want to remove both null and undefined , you can use . isNil or non-strict equality.
In Lodash, you can use _.mapValues:
const users = [
  { Mike: 'true' },
  { Tony: 'True' },
  { Ismael: 'RU' },
];
const normalisedUsers = users.map(user =>
  _.mapValues(user, val => val.toLowerCase() === 'true')
);
console.log(normalisedUsers);
<script src="https://cdn.jsdelivr.net/lodash/4.16.3/lodash.min.js"></script>
You don't have to use lodash. You can use native Array.prototype.map() function:
const users = [
  { Mike: 'true' },
  { Tony: 'True' },
  { Ismael: 'RU' },
];
const normalisedUsers = users.map(user =>
  // Get keys of the object
  Object.keys(user)
   // Map them to [key, value] pairs
   .map(key => [key, user[key].toLowerCase() === 'true'])
   // Turn the [key, value] pairs back to an object
   .reduce((obj, [key, value]) => (obj[key] = value, obj), {})
);
console.log(normalisedUsers);
Functional programming FTW!
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