通过布尔检索数组中的第一个匹配对象

时间:2019-11-24 17:14:06

标签: javascript find boolean

如何检索下面数组中带有free:true的第一个对象而不自己遍历它?有单线吗?

var leftCoords = [{x: 60, y: 192, free: false}, {x: 15, y: 20, free: false}, {x: 435, y: 60, free: true}];

1 个答案:

答案 0 :(得分:0)

您可以使用Array find方法。

var leftCoords = [{x: 60, y: 192, free: false}, {x: 15, y: 20, free: false}, {x: 435, y: 60, free: true}];

// Find it
const found = leftCoords.find(el => el.free);
console.log(found);

// Now we can set it to false
found.free = false;
console.log(leftCoords);