【问题标题】:Check if an element is present in an array that is attribute of an object检查作为对象属性的数组中是否存在元素
【发布时间】:2019-12-17 18:14:52
【问题描述】:

我正在使用 Lodash,我想检查一个元素是否存在于一个数组中,该元素实际上是一个对象的属性(在我的例子中是“特征”),它本身就是数组的一部分。我尝试了 _.some 和 _.find 但我没有成功

const element = 'Hello'
class Example {
    constructor {}

  async featuresCheck () {
    this.Array = [
      { name: something
       surname: somethingelse
       features:[element, ...]
     }, 
    ]

    if (_.some(this.Array,{features:element})){
      console.log('element included')
    } else {
      console.log('element not included')
    }
  } 

}


【问题讨论】:

    标签: javascript arrays object lodash


    【解决方案1】:

    Ori 的回答是正确的。这是一个使用lodash.some 的附加示例。

    const element = 'Hello';
    
    const array = [{
      name: 'foo',
      features: [element, 'bar']
    }, {
      name: 'baz',
      features: []
    }];
    
    const doesFeatureExist = (requiredFeature) => _.some(array, (object) => _.some(object.features, (feature) => feature === requiredFeature));
    
    console.log(doesFeatureExist(element));
    console.log(doesFeatureExist('bar'));
    console.log(doesFeatureExist('foo'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    更新: 以下是使用 JS 类实现所需结果的方法:

    const element = 'Hello'
    
    class Example {
      constructor() {
        this.array = [{
          name: 'foo',
          features: [element, 'bar']
        }, {
          name: 'baz',
          features: []
        }];
      }
    
      featuresCheck(requiredFeature) {
        if (_.some(this.array, (object) => _.some(object.features, (feature) => feature === requiredFeature))) {
          console.log('element included')
        } else {
          console.log('element not included')
        }
    
      }
    }
    
    const example = new Example();
    
    example.featuresCheck(element);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

    【讨论】:

    • 对不起,我在上课时更改了代码 sn-p
    【解决方案2】:

    要检查是否存在,请使用嵌套的Array.some()(或_.some())调用。要查找对象,请使用 Array.find()Array.some()

    const element = 'Hello'
    
    const arr = [
     { features:['not hello'] }, 
     { features:['Hello'] }, 
    ]
    
    const exists = arr.some(o => o.features.some(el => el === element))
    const item = arr.find(o => o.features.some(el => el === element))
    
    console.log('exists: ', exists)
    console.log('item: ', item)

    【讨论】:

    • 我忘了提到我在一个 javascript 类中,所以当我运行你的代码时,它给了我 TypeError "Cannot set property 'features' of undefined"
    • 由于这里的代码没有设置任何东西,你做错了什么有问题。运行 sn -p 看看它是否有效,然后看看你哪里出错了。
    • @Drun 如果您使用的是类,则应更新问题中的代码 sn-p。
    • 好的,我做到了,请看一下
    猜你喜欢
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多