admin管理员组文章数量:1399217
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.
本文标签: javascriptJSON Get Items by ValueStack Overflow
版权声明:本文标题:javascript - JSON Get Items by Value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744132951a2592260.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论