使用 jQuery 过滤 JavaScript 数组中的项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2085012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filter items in JavaScript Array using jQuery
提问by Israfel
I have a JavaScript array as below which I need to filter to get the correct child values from the test data below.
我有一个 JavaScript 数组,如下所示,我需要对其进行过滤以从下面的测试数据中获取正确的子值。
var arrChildOptions2 = [
{Parent:'opt1',Value:'opt1',Text:'Parent1 - Child 1'},
{Parent:'opt2',Value:'opt1',Text:'Parent 2 - Child 1'},
{Parent:'opt2',Value:'opt2',Text:'Parent 2 - Child 2'}
];
The values are used to populate a dropdown based on the change event of a parent dropdown as below.
这些值用于根据父下拉列表的更改事件填充下拉列表,如下所示。
$(function() {
$('#ddl1').change(function() {
$('#ddl2 option:gt(0)').remove();
$('#ddl2').addItems('#ddl2', arrChildOptions2[Parent=opt2]);
});
});
where additems is a function that loops through the array. Problem is I can't get it to filter by parent, I've tried using containsand the above arrChildOptions2[Parent=opt2]but I can't get it to filter, I'd prefer to find a neat solution rather than use a for loop? Any ideas, cheers
其中 additems 是一个循环遍历数组的函数。问题是我无法通过父级过滤它,我尝试使用contains和上面的arrChildOptions2[Parent=opt2]但我无法过滤它,我更愿意找到一个简洁的解决方案而不是使用for 循环?任何想法,欢呼
回答by Phil.Wheeler
You might have more luck using the jQuery.grep()function rather than messing around with loops.
使用jQuery.grep()函数而不是使用循环可能会更幸运。
This function "Finds the elements of an array which satisfy a filter function. The original array is not affected".
此函数“查找满足过滤器函数的数组元素。原始数组不受影响”。
回答by Blazemonger
array.filter()exists in vanilla JavaScript:
array.filter()存在于原生 JavaScript 中:
function isBigEnough(element) {
return element >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
That documentation page includes a polyfill for older browsers:
该文档页面包含用于旧浏览器的 polyfill:
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisArg */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun !== "function")
throw new TypeError();
var res = [];
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i];
// NOTE: Technically this should Object.defineProperty at
// the next index, as push can be affected by
// properties on Object.prototype and Array.prototype.
// But that method's new, and collisions should be
// rare, so use the more-compatible alternative.
if (fun.call(thisArg, val, i, t))
res.push(val);
}
}
return res;
};
}
回答by KdPurvesh
Yes try jquery grep, like this:
是的,试试 jquery grep,像这样:
arr = jQuery.grep( JSON_ARRAY, index);

