要过滤不是严格数组的条目,因此.filter
在其原型上没有属性,但仍可迭代(如document.getElementsByTagName
),您可以使用
Array.prototype.filter.call(collection, function filterFunction(el, index, collection) {
...
});
或者简写
[].filter.call(collection, function filterFunction(el, index, collection) {
...
});
对于不可迭代的对象,但您仍然希望过滤属性并获取通过过滤的键数组,您可以Object.keys
像这样组合:
var obj = { one: 1, two: 2, three: 3, four: 4 };
var filtered = Object.keys(obj).filter(function(key) {
return obj[key] % 2 === 0;
}); //filtered == ['two', 'four']
然后,您可以创建一个包含这些属性的新对象:
var filteredObj = filtered.reduce(function(newObj, currentKey) {
newObj[currentKey] = obj[currentKey]; //Add the original value to the new object
return newObj; //Return the new object to continue iteration
}, {}) // Begin iteration with a blank object
//filteredObj is now { two: 2, four: 4 }
以上甚至可以组合成一个函数!
function filterObject(obj, testCallback) {
return Object.keys(obj).filter(function(key, index, array) {
return testCallback(obj[key], index, array); //Call original filter but pass the property
}).reduce(function(newObj, currentKey) {
newObj[currentKey] = obj[currentKey]; //Add the original value to the new object
return newObj; //Return the new object to continue iteration
}, {}); // Begin iteration with a blank object
}
并像这样使用:
var obj = { one: 1, two: 2, three: 3, four: 4 };
var filteredObj = filterObject(obj, function(el) { return el % 2 === 0 });