'JS list of dictionaries, get first value by condition
Given a list of dictionaries in JS, I want to get the first one that is enabled and not deleted.
The dictionary will look like this:
objects= [{'name':'a', 'width': 100, 'deleted': true, 'enabled': true},
{'name':'b', 'width': 200, 'deleted': false, 'enabled': false},
{'name':'c', 'width': 300, 'deleted': false, 'enabled': true},
{'name':'d', 'width': 400, 'deleted': true, 'enabled': true},
I used to take the first one by using objects[0] but now I need to tkae the deleted and enabled in consideration. How can I get the first relevant value? so the results should be {'name':'c', 'width': 300, 'deleted': false, 'enabled': true}
Solution 1:[1]
Find Method
You can use the Array.find method to find the first element that matches a given condition.
const solution = objects.find(o => o.enabled && !o.deleted);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
