Querying javascript objects using jQuery or other known js library
What is the best way to apply queries (such as regular expressions) on javascript objects to obtain a subset of some array or collection that follow some criteria, are there such plugin for jQuery, or 开发者_Go百科some way to use jQuery or other known js library for this purpose?
for example:
var x=[{ firstName: "Tony",lastName="Mike" }, { firstName: "John", lastName="Jan"}];
var y = ????;//the first names of the objects in x where their last names follow the regular expression : bla-bla-bla
It appears as you are looking for JSONpath or the like.
using jQuery:
var x = [
{ firstName: "Sakher",lastName:"Sawan" },
{ firstName: "John", lastName:"Jan"}
],
y = $(x).map(function(a, obj){
return /^S/.test(obj.lastName) ? obj.firstName : null
});
Note that in some browsers you don't have to use jQuery to do this, as you can just as well use x.map
in browsers that have Array.prototype.map
(older browsers don't)
You should use some frameworks like dojo for doing these kind of operations.
look at the sample grid
http://dojotoolkit.org/reference-guide/dojox/grid/DataGrid.html
you can do all kind of operations on that.
It seems that you can do it by JS itself:
var re = ...; // regular espression
var y = [....]; // input array
var x = y.filter(function(el) { return re.test(el.firstName) } );
In x
you will have filtered array where each element satisfy your conditions.
Check this link.
var jsonArray = [
{ "user": { "id": 100, "screen_name": "d_linq" }, "text": "to objects" },
{ "user": { "id": 130, "screen_name": "c_bill" }, "text": "g" },
{ "user": { "id": 155, "screen_name": "b_mskk" }, "text": "kabushiki kaisha" },
{ "user": { "id": 301, "screen_name": "a_xbox" }, "text": "halo reach" }
]
// ["b_mskk:kabushiki kaisha", "c_bill:g", "d_linq:to objects"]
var queryResult = Enumerable.From(jsonArray)
.Where(function (x) { return x.user.id < 200 })
.OrderBy(function (x) { return x.user.screen_name })
.Select(function (x) { return x.user.screen_name + ':' + x.text })
.ToArray();
// shortcut! string lambda selector
var queryResult2 = Enumerable.From(jsonArray)
.Where("$.user.id < 200")
.OrderBy("$.user.screen_name")
.Select("$.user.screen_name + ':' + $.text")
.ToArray();
精彩评论