Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查作为对象属性的数组中是否存在元素_Javascript_Arrays_Object_Lodash - Fatal编程技术网

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

Javascript 检查作为对象属性的数组中是否存在元素,javascript,arrays,object,lodash,Javascript,Arrays,Object,Lodash,我使用的是Lodash,我想检查数组中是否存在一个元素,该元素实际上是一个对象的属性(在我的例子中是“特征”),该对象本身就是数组的一部分。我尝试了一些,但没有成功 const element = 'Hello' class Example { constructor {} async featuresCheck () { this.Array = [ { name: something surname: somethingelse

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

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')
    }
  } 

}



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

const元素='Hello'
常数arr=[
{features:['nothello']},
{功能:['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)
的答案是正确的。下面是一个使用的附加示例

const元素='Hello';
常量数组=[{
名称:“foo”,
特征:[元素,'条']
}, {
名称:“baz”,
特色:[]
}];
const doesFeatureExist=(requiredFeature)=>\.some(数组,(对象)=>\.some(object.features,(feature)=>feature==requiredFeature));
log(doesFeatureExist(元素));
log(doesFeatureExist('bar');
log(doesFeatureExist('foo')

我忘了提到我在一个javascript类中,所以当我运行你的代码时,它会给我一个TypeError“Cannotset property'features'of undefined”,因为这里的代码没有设置任何内容,所以你在做错事。运行代码段以查看其是否有效,然后查看错误所在。@Drun如果您使用的是类,则应更新问题中的代码段。好的,我已经更新了,请现在查看抱歉,我更改了代码段,因为我在类中