Es6 equivalent to findWhere underscore

I'm looking to find out how I take the _.findWhere underscore and turn it into my own javascript es6?

 _.findWhere($scope.template, {id: $scope.approveTemplate}) 
+5
source share
2 answers

While the Limit Response is great for the specific example you submitted, it should handle every usecase _.findWhere :

 function myFindWhere(array, criteria) { return array.find(item => Object.keys(criteria).every(key => item[key] === criteria[key])) } 

It returns the first element from the input array, for which all the specific properties of the criteria are matched (or undefined if there is no such element), which, in my opinion, is a _.findWhere contract.

Here's how to use it to process your example:

 myFindWhere($scope.template, {id: $scope.approveTemplate}) 

And here are some test cases I used for testing:

myFindWhere ([{{"a": 0, "b": 1}, {"a": 1}, {"b": 1}], {"a": 0})
> Object {a: 0, b: 1}
myFindWhere ([{{"a": 0, "b": 1}, {"a": 1}, {"b": 1}], {"b": 0})
> undefined
myFindWhere ([{{"a": 0, "b": 1}, {"a": 1}, {"b": 1}], {"b": 1})
> Object {a: 0, b: 1}
myFindWhere ([{{"a": 0, "b": 1}, {"a": 1}, {"b": 2}], {"b": 2})
> Object {b: 2}

+5
source
 $scope.template.find(t => t.id === $scope.approveTemplate) 
+11
source

All Articles