What is the most efficient way to filter an JavaScript array of objects based on a key-value?
For example: I’d like to select items by color in the following array:
[{Id:1, color:”blue”},{Id:2, color:”green”},{Id:3, color:”blue”},{Id:4, color:”red”}]
There’s an easy syntax for selecting items by property in languages like CSS or xslt, but I can’t find an equivalent for JSON.
You can’t filter JSON strings directly — with ease, at least — without first parsing them into JavaScript objects:
But note that JSON parsers are normally strict — object keys must be strings (http://json.org):
After that, you can use
filteron the returnedArray:To support older browsers, include json2.js for
JSON.parsealong with the “Compatibility” code offered by MDN forfilter(or use the ES5-shim for a collection of such definitions).