2017-12-02 97 views
1

如何获得只有第一对象时,两个对象匹配的if语句

const cars = [{ 
 
\t brand: 'BMW', 
 
\t year: '1997' 
 
}, { 
 
\t brand: 'BMW', 
 
\t year: '2011' 
 
}] 
 
Object.keys(cars).forEach(function(x) { 
 
\t if (cars[x].brand == "BMW") { 
 
\t \t console.log(cars[x]); 
 
\t } 
 
});

如何CONSOLE.LOG阵列相匹配的品牌“宝马”的只有第一个对象? *它必须是与对象键

+0

'cars'是一个数组。为什么要使用Object.keys()'? Oo – Andreas

回答

0

你可以拿Array#some,如果发现一个品牌返回true - 那么迭代停止。

const cars = [{ brand: 'BMW', year: '1997' }, { brand: 'BMW', year: '2011' }]; 
 

 
Object.keys(cars).some(function(x) { 
 
    if (cars[x].brand == "BMW") { 
 
     console.log(cars[x]); 
 
     return true; 
 
    } 
 
});

+0

这就是我正在寻找的,非常简单的heh。谢谢! :) – Hatchling

2

用户array.find的溶液中,将只返回第一匹配部件。

const cars = [{ 
 
\t brand: 'BMW', 
 
\t year: '1997' 
 
}, { 
 
\t brand: 'BMW', 
 
\t year: '2011' 
 
}] 
 

 
console.log(cars.find(car=>car.brand ==='BMW'));

编辑

因为你需要Object.Keys的解决方案,你可以使用array.some()

const cars = [{ 
 
\t brand: 'BMW', 
 
\t year: '1997' 
 
}, { 
 
\t brand: 'BMW', 
 
\t year: '2011' 
 
}] 
 

 
Object.keys(cars).some(function(ele) { 
 
\t if (cars[ele].brand == "BMW") { 
 
     console.log(cars[ele]); 
 
     return true; 
 
\t } 
 
});

+0

OP说:“它必须是object.keys()的解决方案” –

+0

@AndrewLohr是更新,但我不知道为什么OP需要:) – Sajeetharan

+0

是与上述代码他只需要添加一个检查 – Sajeetharan

0

以上使用Array.prototype.find()的答案绝对是你要找的。

但是,如果您在其他情况下遇到此问题:当您使用for循环并且想要尽早结束循环时,可以使用“break”关键字。

break关键字不适用于forEach,但是您不应该使用forEach - 它具有较少的浏览器支持,并且比老式for循环要慢。

+0

'阵列.prototype.find()'是解决方案,但您建议不要使用'.forEach()',因为它的浏览器支持? O.o'.forEach()'在每个浏览器中都可用,'.find()'不是 – Andreas

+0

我其实并不知道find没有得到很好的支持,因为我没有真正使用它。我真的建议只使用for循环和break,并且只接受find,因为另一个用户已经提到过它,它是OP问题的确切方法。 –

0

这将有助于你

var Exception = {}; 
 
const cars = [{ 
 
\t brand: 'BMW', 
 
\t year: '1997' 
 
}, { 
 
\t brand: 'BMW', 
 
\t year: '2011' 
 
}] 
 
try{ 
 
Object.keys(cars).forEach(function(x) { 
 
\t if (cars[x].brand == "BMW") { 
 
\t \t console.log(cars[x]); 
 
     throw Exception; 
 
\t } 
 
}); 
 
}catch(e){ 
 
    if (e !== Exception) throw e; 
 
}

0

可以使用Object.keys(cars).find(function)象下面这样:

const cars = [{ 
 
\t brand: 'BMW', 
 
\t year: '1997' 
 
}, { 
 
\t brand: 'BMW', 
 
\t year: '2011' 
 
}] 
 

 
Object.keys(cars).find(function(x) { 
 
if (cars[x].brand == "BMW") { 
 
    console.log(cars[x]); 
 
    return true; 
 
    } 
 
});