pertrai1
pertrai1

Reputation: 4318

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})

Upvotes: 10

Views: 6481

Answers (2)

Aaron
Aaron

Reputation: 24802

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}

Upvotes: 13

Lim H.
Lim H.

Reputation: 10050

$scope.template.find(t => t.id === $scope.approveTemplate)

Upvotes: 14

Related Questions