我有如下所示的JSONArray
[
{
"id": 1,
"firstName": "abc",
"isActive": true
},
{
"id": 2,
"firstName": "cde",
"isActive": false
},
{
"id": 3,
"firstName": "efg",
"isActive": true
},
{
"id": 4,
"firstName": "ghi",
"isActive": false
}
]
现在,我想使用最有效和最优化的方法从该数组中获得值“ isActive”的值为true的对象。
{
"id": 3,
"firstName": "efg",
"isActive": true
}
更新:
let getLast = items.filter(item => item.isActive === true);
我尝试使用@brk提供的解决方案。但是有什么方法可以使用对象而无需创建新数组。
答案 0 :(得分:2)
第一个filter
,条件为isActive === true
。这将创建一个新数组,然后使用array.length-1
获取最后一个元素
let data = [{
"id": 1,
"firstName": "abc",
"isActive": true
},
{
"id": 2,
"firstName": "cde",
"isActive": false
},
{
"id": 3,
"firstName": "efg",
"isActive": true
},
{
"id": 4,
"firstName": "ghi",
"isActive": false
}
]
let getLast = data.filter(item => item.isActive === true);
console.log(getLast[getLast.length - 1])
答案 1 :(得分:0)
var x=[
{
"id": 1,
"firstName": "abc",
"isActive": true
},
{
"id": 2,
"firstName": "cde",
"isActive": false
},
{
"id": 3,
"firstName": "efg",
"isActive": true
},
{
"id": 4,
"firstName": "ghi",
"isActive": false
}
];
//Try the following line
x.filter(x=>x.isActive).slice(-1).pop()
答案 2 :(得分:0)
var jsonObject = [
{
"id": 1,
"firstName": "abc",
"isActive": true
},
{
"id": 2,
"firstName": "cde",
"isActive": false
},
{
"id": 3,
"firstName": "efg",
"isActive": true
},
{
"id": 4,
"firstName": "ghi",
"isActive": false
}
];
var lastActiveElement = jsonObject.filter( obj => obj.isActive ).pop();
console.log(lastActiveElement);
如果这是您要寻找的