最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

easiest way to search a javascript object list with jQuery? - Stack Overflow

programmeradmin1浏览0评论

What is the easiest way to search a javascript object list with jQuery?

For example, I have the following js config block defined:

var ProgramExclusiveSections =
{
   "Rows":
   [
      { 'ProgramId': '3', 'RowId': 'trSpecialHeader'},
      { 'ProgramId': '3', 'RowId': 'trSpecialRow1' },
      { 'ProgramId': '3', 'RowId': 'trSpecialRow2' },
      { 'ProgramId': '1', 'RowId': 'trOtherInfo' }
   ]
} 

The user has selected Program ID = 3 so I want to get only the "rows" that I have configured in this js config object for Program ID = 3. This will get me the javascript object list:

var rows = ProgramExclusiveSections.Rows

but then I need to filter this down to only where RowId = 3. What's the easiest way for me to do this with jquery?

What is the easiest way to search a javascript object list with jQuery?

For example, I have the following js config block defined:

var ProgramExclusiveSections =
{
   "Rows":
   [
      { 'ProgramId': '3', 'RowId': 'trSpecialHeader'},
      { 'ProgramId': '3', 'RowId': 'trSpecialRow1' },
      { 'ProgramId': '3', 'RowId': 'trSpecialRow2' },
      { 'ProgramId': '1', 'RowId': 'trOtherInfo' }
   ]
} 

The user has selected Program ID = 3 so I want to get only the "rows" that I have configured in this js config object for Program ID = 3. This will get me the javascript object list:

var rows = ProgramExclusiveSections.Rows

but then I need to filter this down to only where RowId = 3. What's the easiest way for me to do this with jquery?

Share Improve this question asked Aug 3, 2011 at 17:09 Manikandan ThangarajManikandan Thangaraj 1,5948 gold badges25 silver badges45 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 8

$.grep()

var matches = $.grep(rows, function (elt)
{
    return elt.ProgramId === '3';
});

$.map() would do it (although $.grep() is more elegant).

var objs= $.map(ProgramExclusiveSections.Rows, function(obj, index) {
    return obj.RowId === "3"? obj : null;
});

This will return an array of the objects with RowId "3" (notice you have a string and not a number).

发布评论

评论列表(0)

  1. 暂无评论