在我的项目中,我有一个数组,包含数千个对象。我需要在数组中搜索一个显式对象。当找到匹配项时,我需要能够访问对象属性。由于性能的原因,我想使用Javascript的.some((函数。但对于我目前所拥有的代码,我只得到了一个"true"作为回报。如果if语句命中,我如何访问里面的属性?
我的代码:
let array = [
{object.uid: 'one',
object.value: 'Hello one'},
{object.uid: 'two',
object.value: 'Hello two'},
{object.uid: 'three',
object.value: 'Hello three'}]
if (array.some(e => e.uid == "two")){
//how do I get object.value here?
};
您需要使用find((方法,而不是some((
let array = [
{uid: 'one',
value: 'Hello one'},
{uid: 'two',
value: 'Hello two'},
{uid: 'three',
value: 'Hello three'}]
const obj = array.find(e => e.uid == "two");
if (obj){
console.log(obj)
};