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.
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.
Share Improve this question asked Nov 11, 2011 at 0:05 ChristopheChristophe 28.2k29 gold badges103 silver badges144 bronze badges2 Answers
Reset to default 7You can't filter JSON strings directly -- with ease, at least -- without first parsing them into JavaScript objects:
var collection = JSON.parse(jsonString);
But note that JSON parsers are normally strict -- object keys must be strings (http://json):
[{ "Id": 1, "color": "blue" }, { "Id": 2, "color": "green" }, ...]
After that, you can use filter
on the returned Array
:
var filtered = collection.filter(function (item) {
return item.color === "blue";
});
console.log(filtered[0]); // [Object] :: { Id: 1, color: "blue" }
To support older browsers, include json2.js for JSON.parse
along with the "Compatibility" code offered by MDN for filter
(or use the ES5-shim for a collection of such definitions).
JSON is not a language. I assume you mean javascript. And you will have to write it yourself there is no built in way.