I am looking to find out how I would take underscore _.findWhere
and turn it into es6 native javascript?
_.findWhere($scope.template, {id: $scope.approveTemplate})
$scope.template.find(t => t.id === $scope.approveTemplate)
While Lim's answer is great for the specific example you posted, this one should handle every usecase of _.findWhere
:
function myFindWhere(array, criteria) {
return array.find(item => Object.keys(criteria).every(key => item[key] === criteria[key]))
}
It returns the first item from the input array for which all defined properties of the criteria are matched (or undefined
if there is no such item), which I believe is the contract of _.findWhere
.
Here's how to use it to handle your example :
myFindWhere($scope.template, {id: $scope.approveTemplate})
And here are a few test case I used to test it :
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With