繁体   English   中英

获取对象属性值

[英]Getting object property value

我的数组如下:

let arr = [
    {type: "Benzine", active: false},
    {type: "Diesel", active: false},
    {type: "Electricity", active: false}
]

我有一个函数,我想在其中获取该数组的active属性的值:

function isChecked(filterName) {
    return arr.filter(f => f.type === filterName).map(c => c.active)[0];
}

效果很好,最后是[0] 有没有办法在末尾没有[0]情况下显示活动属性值?

不,只要您使用filter ,就没有。
[0]用于从该过滤器中获取第一个结果。

由于您只是返回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"));

您可以使用find来获取数组的第一个匹配元素,而不是使用filter

function isChecked(filterName) {
    var elem = arr.find(f => f.type === filterName);
    return elem ? elem.active : false;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM