Einträge zu filtern, die nicht streng Arrays sind, und damit die auf ihren Prototyp .filter
Eigenschaft nicht haben, sind aber immer noch iterable (wie document.getElementsByTagName
) Sie
Array.prototype.filter.call(collection, function filterFunction(el, index, collection) {
...
});
Oder die Kurz
verwenden können
[].filter.call(collection, function filterFunction(el, index, collection) {
...
});
wie für Objekte, die nicht iterable sind, aber Sie wollen immer noch Eigenschaften filtern und eine Reihe von Schlüsseln zu erhalten, die Filterung übergeben, können Sie mit Object.keys
kombinieren wie so:
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']
Dann können Sie ein neues Objekt mit diesen Eigenschaften erstellen:
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 }
Das Obige kann auch in eine Funktion kombiniert werden!
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
}
Und wie diese:
var obj = { one: 1, two: 2, three: 3, four: 4 };
var filteredObj = filterObject(obj, function(el) { return el % 2 === 0 });
Diese ist eine kanonische Frage, um andere als Duplikate zu schließen. – Scimonster