chefcurry7
chefcurry7

Reputation: 5251

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?

Upvotes: 7

Views: 32873

Answers (3)

castletheperson
castletheperson

Reputation: 33516

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>

Upvotes: 13

Michał Perłakowski
Michał Perłakowski

Reputation: 92689

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!

Upvotes: 8

James111
James111

Reputation: 15903

You don't need lodash to achieve this, just use a for loop. Here is an example

var users = [
  { Mike:    'true' },
  { Tony:    'True' },
  { Ismael:  'RU' }
];

for (key in users) {
   if (users[key] == 'true' || users[key] == 'True') {
      users[key] = true
   } else {
     users[key] = false
   }
}

What this is doing is, if your value is 'true' or 'True' then assign a boolean val of true to your object & else assign false.

Edit

You could also do it the shorthand way, as suggested by 4castle:

users[key] = users[key] == 'true' || users[key] == 'True';

Simply replace the if/else block with this one line.

Upvotes: -2

Related Questions