Skip to content
Advertisement

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}

Advertisement

Answer

Use find, if you want to find the first object that match the find condition in the array.

Use filter, If you want to find all the objects that match the filter condition in the array.

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}
          ];
          
var findOne = objects.find(x => !x.deleted && x.enabled);
console.log(findOne);

var findMany = objects.filter(x => !x.deleted && x.enabled);
console.log(findMany);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement