Reputation: 5251
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
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
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
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.
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