是否可以讓一個陣列過濾另一個陣列以匹配每個字符?
我有一組日志和一個過濾器,如下所示:
logs = [{id:1, log: "log1"}], {id:2, log: "log2"}, {id:3, log: "fail"}
filter = ["log"]
它應該回傳
[{id:1, log: "log1"}, {id:2, log: "log2"}]
如果我的過濾器是
filter = ["1", "fai"]
輸出將是
[{id:1, log: "log1"}, {id:3, log: "fail"]
uj5u.com熱心網友回復:
您可以將函式Array.prototype.filter
與函式一起使用,Array.prototype.some
以過濾掉與過濾器不匹配的物件。
const match = (filter, key, array) => array.filter(o => filter.some(c => o[key].includes(c))),
array = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}];
console.log(match(["log"], "log", array));
console.log(match(["1", "fai"], "log", array));
uj5u.com熱心網友回復:
您可以執行以下操作:
const logs = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}]
const searches = ["1", "fai"]
const matchingLogs = logs.filter(l => {
return searches.some(term => l.log.includes(term))
})
uj5u.com熱心網友回復:
let logs = [{id:1, log: "log1"}, {id:2, log: "log2"}, {id:3, log: "fail"}];
let filter = ["1", "fai"];
/*
* filter the array using the filter function.
* Find any given string in the array of objects.
* If you have a match, it will be added to the
* array that will be returned
*/
let matches = logs.filter(function(object) {
return !!filter.find(function(elem) {
return -1 !== object.log.indexOf(elem);
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495964.html
標籤:javascript 数组 筛选