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 02 Answers
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).