0

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.

Christophe
  • 27,383
  • 28
  • 97
  • 140

2 Answers2

7

You 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.org):

[{ "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).

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • Sorry, what do you mean by "the compatibility code offered by MDN"? – Christophe Nov 11 '11 at 00:29
  • 1
    @Christophe Sorry. I was referring to the code listed under the ["Compatibility" heading](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Compatibility). – Jonathan Lonowski Nov 11 '11 at 00:30
0

JSON is not a language. I assume you mean javascript. And you will have to write it yourself there is no built in way.

Ariel
  • 25,995
  • 5
  • 59
  • 69