7

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?

3
  • 2
    Does 'RU' become false? Commented Nov 3, 2016 at 4:30
  • yes it becomes false Commented Nov 3, 2016 at 4:31
  • sorry edited, it should be false. so anything with "true" or "True" should be true, anything else false. Commented Nov 3, 2016 at 4:32

3 Answers 3

13

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, it's much simpler than my solution.
8

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!

1 Comment

Several answers (including this one) start with, essentially, "you don't need lodash for that". And how many more across SO! Although it is useful to point to alternate, possibly simpler solutions, my immediate reaction is always: "And you're not answering the question!"
-2

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.

1 Comment

Perhaps more simply: users[key] = users[key] === 'true' || users[key] === 'True';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.