简体   繁体   English

替换对象值lodash

[英]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 . 我有这个问题,我想我的正常化对象,基本上取代“真”或“真”与布尔true什么都应该是false

By the way I may have the syntax for users wrong, chrome is telling me users.constructor == Object and not Array . 顺便说一下,我可能有错误的users语法,chrome告诉我users.constructor == Object而不是Array

How can I achieve this using lodash? 我如何使用lodash实现这一目标?

In Lodash, you can use _.mapValues : 在Lodash中,您可以使用_.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> 

You don't have to use lodash. 你不必使用lodash。 You can use native Array.prototype.map() function: 您可以使用本机Array.prototype.map()函数:

 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! 功能编程FTW!

You don't need lodash to achieve this, just use a for loop. 你不需要lodash来实现这一点,只需使用for循环。 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. 这样做,如果你的值是'true'或'True',那么为你的对象赋一个布尔值为true,否则赋值为false。

Edit 编辑

You could also do it the shorthand way, as suggested by 4castle : 您也可以按照4castle的建议采用速记方式:

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

Simply replace the if/else block with this one line. 只需用这一行替换if / else块即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM