javascript - JSON Get Items by Value - Stack Overflow

What is the most efficient way to filter an JavaScript array of objects based on a key-value?For exampl

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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):

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744132951a4559922.html

相关推荐

  • javascript - JSON Get Items by Value - Stack Overflow

    What is the most efficient way to filter an JavaScript array of objects based on a key-value?For exampl

    8天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信