最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace object values lodash - Stack Overflow

programmeradmin10浏览0评论

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?

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?

Share Improve this question edited Nov 3, 2016 at 4:33 chefcurry7 asked Nov 3, 2016 at 4:27 chefcurry7chefcurry7 5,24112 gold badges30 silver badges33 bronze badges 3
  • 2 Does 'RU' bee false? – castletheperson Commented Nov 3, 2016 at 4:30
  • yes it bees false – chefcurry7 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. – chefcurry7 Commented Nov 3, 2016 at 4:32
Add a ment  | 

3 Answers 3

Reset to default 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/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!

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.

发布评论

评论列表(0)

  1. 暂无评论