Moons
Moons

Reputation: 3854

Jquery filter for nested objects

My code is:

 colModel: [

    { display: 'Grade', name: 'Grade', width: 40, align: 'center' },
    { display: 'Grade ID', name: 'ID', width: 180, align: 'left' },
    { display: 'Organization ID', name: 'Organization_ID', width: 120, align: 'left' },
    { display: 'Organization Name', name: 'Organization_Name', width: 130, align: 'left', hide: true }
    ]

This is passed as a object to a function.

i want to filter it like

// This worked

   alert(colModel[0].display);

   var obj = colModel.filter(function () {
               return $(this).name == "Grade"; });

  alert(obj.display);

But this come to be undefined.

ANy help is appreciated

Edit:

The object is passed as a option to a plugin:

$('#filteredResult').FilteredPagedTable({ url: "http://localhost:2014/mySer.svc/GetFilteredPaged", grid: true, pageSize: 4, pageNo: 0, columnName: "ID", IsAscending: true, filteredColumn: $('#ddlColumns').val(), SearchedValue: $('#txtSearchTextBox').val() ,

    colModel: [

    { display: 'Grade', name: 'Grade', width: 40, align: 'center' },
    { display: 'Grade ID', name: 'ID', width: 180, align: 'left' },
    { display: 'Organization ID', name: 'Organization_ID', width: 120, align: 'left' },
    { display: 'Organization Name', name: 'Organization_Name', width: 130, align: 'left', hide: true }
    ]

 });

Upvotes: 1

Views: 946

Answers (3)

Fenton
Fenton

Reputation: 250942

I've worked this one out...

Where you have

alert(obj.display);

You should use

alert(obj[0].display);

As filter returns an array of matches - even when only one result is found.

See it working here: http://jsfiddle.net/Sohnee/N6W7r/

Upvotes: 1

Aron Woost
Aron Woost

Reputation: 20668

Why using jQuery?

var colModelFiltered = colModel.filter(function(element, index, array){
 return element.name === "Grade";
});

EDIT (by Kamal Deep Singh)

You also need to put:

 if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun /*, thisp*/) {
  var len = this.length >>> 0;
   if (typeof fun != "function")
   throw new TypeError();

var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
  if (i in this) {
    var val = this[i]; // in case fun mutates this
    if (fun.call(thisp, val, i, this))
    res.push(val);
  }
}
return res;
};
}

in the document.ready() event to make it work on IE too.

More details are on:
Javascript: How to filter object array based on attributes?

Upvotes: 0

Stefan
Stefan

Reputation: 5662

var matchedCols = {};
$.each(colModel, function(i) {
    if (this.name == "Grade") {
      matchedCols[i] = this;
    }
});

See http://jsfiddle.net/acVbZ/

Upvotes: 1

Related Questions