Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace object values lodash

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?

like image 975
chefcurry7 Avatar asked Nov 03 '16 04:11

chefcurry7


People also ask

How do you replace 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.

How do I remove a property from object Lodash?

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.

How do you remove undefined and null values from an object using Lodash?

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.


2 Answers

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>
like image 188
4castle Avatar answered Sep 16 '22 19:09

4castle


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!

like image 44
Michał Perłakowski Avatar answered Sep 16 '22 19:09

Michał Perłakowski