Saw
Saw

Reputation: 6426

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 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

Upvotes: 0

Views: 364

Answers (5)

user578895
user578895

Reputation:

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)

Upvotes: 1

Shahin
Shahin

Reputation: 12841

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();

Upvotes: 1

c-smile
c-smile

Reputation: 27460

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.

Upvotes: 1

kobe
kobe

Reputation: 15835

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.

Upvotes: 1

c-smile
c-smile

Reputation: 27460

It appears as you are looking for JSONpath or the like.

Upvotes: 2

Related Questions