Per filtrare le voci che non sono strettamente array, e quindi non hanno la proprietà .filter
il loro prototipo, ma sono ancora iterabile (come document.getElementsByTagName
), è possibile utilizzare
Array.prototype.filter.call(collection, function filterFunction(el, index, collection) {
...
});
O la stenografia
[].filter.call(collection, function filterFunction(el, index, collection) {
...
});
per quanto riguarda gli oggetti che non sono iterabile, ma vuoi comunque filtrare le proprietà e ottenere una serie di chiavi che passano il filtro, è possibile combinare con Object.keys
come così:
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']
Quindi, è possibile creare un nuovo oggetto che contiene le proprietà:
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 }
Quanto sopra può anche essere combinati in una funzione!
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
}
E utilizzare in questo modo:
var obj = { one: 1, two: 2, three: 3, four: 4 };
var filteredObj = filterObject(obj, function(el) { return el % 2 === 0 });
Questo è inteso come una domanda canonica per chiudere gli altri come duplicati di. – Scimonster