Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 equivalent of underscore findWhere

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})
like image 734
pertrai1 Avatar asked May 18 '16 13:05

pertrai1


2 Answers

$scope.template.find(t => t.id === $scope.approveTemplate)
like image 104
Lim H. Avatar answered Oct 18 '22 00:10

Lim H.


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}

like image 11
Aaron Avatar answered Oct 17 '22 23:10

Aaron