Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  193] [ 6]  / answers: 1 / hits: 115629  / 13 Years ago, sat, june 4, 2011, 12:00:00
var set = [{color:blue},{color:green},{color:red},{color:green}];


I'd like to be able to do something like a db call, set.find({color:green}) and have it return an array full of objects that contain that property.


More From » javascript

 Answers
24

Using Array#filter, for this particular case the code would look like



var results = set.filter(function (entry) { return entry.color === green; });


Array#filter is not implemented in some older browsers, so see the linked article for a backward compatibility shim, or better yet get a full-fledged ES5 shim.



For the more general case, it's just a matter of extending this idea:



function findByMatchingProperties(set, properties) {
return set.filter(function (entry) {
return Object.keys(properties).every(function (key) {
return entry[key] === properties[key];
});
});
}

var results = findByMatchingProperties(set, { color: green });


Again, I am using ECMAScript 5 methods Object.keys and Array#every, so use an ES5 shim. (The code is doable without an ES5 shim but uses manual loops and is much less fun to write and read.)


[#91867] Thursday, June 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dusty

Total Points: 739
Total Questions: 97
Total Answers: 85

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;