![](/img/trans.png)
[英]How to chain multiple filter functions in javascript with multiple conditions array
[英]Javascript Filter an array based on multiple conditions using native functions
我有一種情況,我需要根據某些條件過濾一組對象。 這是什么
message
, type
, keyValues
keyValues
是一個數組,最多可以有 3 個不同的項目。 每個元素的節點是key
和value
key
可以具有以下 3 個值之一by-date
, by-unique-object
, by-related-object
by-date
的值將具有日期值 objectby-unique-object
值, by-related-object
將具有 object 為
value: {
uri: "object-uri-1"
}
uri
具有特定的模式,並且對於by-unique-object
和by-related-object
兩種類型都是相同的。 所以,從給定的錯誤數組中,我只需要過濾那些只有by-date
獲得的記錄,並且不應該有其他 2 種類型的 URI 模式
這是我所做的 -
let errors = [
{
message: "Error message 1",
type: "error",
keyValues: [
{
key: "by-date",
value: {
date: {year:2020, month: 4, day: 6}
}
},
{
key: "by-unique-object",
value: {
uri: "object-uri-1"
}
},
{
key: "by-related-object",
value: {
uri: "object-uri-1"
}
},
]
},
{
message: "Error message 2",
type: "error",
keyValues: [
{
key: "by-date",
value: {
date: {year:2020, month: 4, day: 5}
}
}
]
},
{
message: "Error message 3",
type: "error",
keyValues: [
{
key: "by-date",
value: {
date: {year:2020, month: 4, day: 6}
}
},
{
key: "by-unique-object",
value: {
uri: "object-uri-3"
}
}
]
},
{
message: "Error message 4",
type: "warning",
keyValues: [
{
key: "by-unique-object",
value: {
uri: "object-uri-4"
}
},
{
key: "by-related-object",
value: {
uri: "object-uri-4"
}
}
]
},
{
message: "Error message 5",
type: "warning",
keyValues: [
{
key: "by-date",
value: {
date: {year:2020, month: 4, day: 8}
}
},
{
key: "by-related-object",
value: {
uri: "object-uri-4"
}
}
]
},
{
message: "Error message 6",
type: "warning",
keyValues: [
{
key: "by-date",
value: {
date: {year:2020, month: 4, day: 9}
}
}
]
}
];
const matchObjectUriPattern = (uri) => /object-uri-.*/g.test(uri);
const hasByDate = (item) => item.key === "by-date" && item.value && item.value.date;
const hasUniqueObject = (item) => item.key === "by-unique-object" && matchObjectUriPattern(item.value.uri);
const hasRelatedObject = (item) => item.key === "by-related-object" && matchObjectUriPattern(item.value.uri);
const checkOnlyByDate = (error) => {
let keyValues = error && error.keyValues ? error.keyValues : [];
let byDate = keyValues.find(hasByDate);
let byUniqueObject = keyValues.find(hasUniqueObject);
let byRelatedObject = keyValues.find(hasRelatedObject);
return byDate && (!byUniqueObject && !byRelatedObject);
};
const filteredErrors = errors.filter(checkOnlyByDate);
console.log(JSON.stringify(filteredErrors));
我做的很好,但是有更好的方法嗎? 或者一些更好的方法來處理這個?
我喜歡您的解決方案:根據您的要求,我提出了:
const filteredErrors = errors.filter(({keyValues}) =>
keyValues.every(({key}) => key === "by-date"))
它只返回那些keyValues
數組只包含key
=== "by-date" 的對象的錯誤消息
我不能說這比您提供的更好或更差,因為我不確定您可能會如何使用此代碼。 但我想添加我自己對這個問題的解釋。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.