【问题标题】:Check object for certain value using lodash使用 lodash 检查对象的特定值
【发布时间】:2019-05-03 15:41:40
【问题描述】:

我想使用 lodash 检查某个属性是否具有某个值。下面的代码打印出错误。如何正确检查值?

code example

const ob = {
 archived:true,
 done: true
}

console.dir(_.includes(ob.archived, true));

【问题讨论】:

标签: lodash


【解决方案1】:

您需要将_.includes 直接用于对象,这是一个示例:

const ob = {archived:true};

_.includes(ob, true); // true

如果你只需要检查一个值,你可以使用这个:

const ob = {archived:true, done: true};

_.includes(_.pick(ob, ['archived']), true); // true

【讨论】:

    【解决方案2】:

    您可以使用_.matchesProperty()。该方法生成一个函数,该函数接受一个对象,如果该对象包含指定的属性和值,则返回true

    const hasArchivedTrue = _.matchesProperty('archived', true)
    
    const ob = {
     archived: true,
     done: true
    }
    
    console.log(hasArchivedTrue(ob)) // true
    console.log(hasArchivedTrue({})) // false
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

    【讨论】:

      猜你喜欢
      • 2017-01-20
      • 1970-01-01
      • 2021-10-19
      • 2017-03-13
      • 2017-12-11
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多