[英]Getting object property value
My array is the following:我的数组如下:
let arr = [
{type: "Benzine", active: false},
{type: "Diesel", active: false},
{type: "Electricity", active: false}
]
And I have a function where I want to get value of the property active
of that array:我有一个函数,我想在其中获取该数组的active
属性的值:
function isChecked(filterName) {
return arr.filter(f => f.type === filterName).map(c => c.active)[0];
}
That works fine, with [0]
at the end.效果很好,最后是[0]
。 Is there any way to show the active property value without [0]
at the end?有没有办法在末尾没有[0]
情况下显示活动属性值?
No, as long as you use filter
, there's not.不,只要您使用filter
,就没有。
The [0]
is used to get the first result from that filter. [0]
用于从该过滤器中获取第一个结果。
Since you're just returning the value of active
, you could use Array.prototype.some
, instead:由于您只是返回active
的值,因此可以改用Array.prototype.some
:
let arr = [ {type: "Benzine", active: false}, {type: "Diesel", active: false}, {type: "Electricity", active: true} ]; function isChecked(filterName){ // Is there an element in the array that matches the filter AND is active? return arr.some(f => f.type === filterName && f.active); } console.log("Diesel:", isChecked("Diesel")); console.log("Electricity:", isChecked("Electricity"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.