检查元素是否存在于作为对象属性的数组中

时间:2019-12-17 18:14:52

标签: javascript arrays object lodash

我正在使用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')
    }
  } 

}


2 个答案:

答案 0 :(得分:0)

要检查是否存在,请使用嵌套的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)

答案 1 :(得分:0)

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>