我需要检查字符串是否具有一些值的indexOf。我想避免这样的事情:
objectId.getIdSnapshot().values()
我试图创建一个像 let filter = tasks.filter(
x =>
x.eventData.workflow_name === brand &&
(x.eventData.task_queue_name.indexOf('Value1') == -1 &&
x.eventData.task_queue_name.indexOf('_Value2') == -1 &&
x.eventData.task_queue_name.indexOf('Value3') == -1 &&
x.eventData.task_queue_name.indexOf('BANG_Value4') == -1)
)
这样的数组,并在一行中编写indexOf条件。
是否可以避免一堆const VALUES_TO_SKIP = ['Value1', ...]
?
答案 0 :(得分:2)
您可以像这样使用Array.some
或Array.every
:
// The values to Test out
const arrayOfValue = [
'Value1',
'_Value2',
'Value3',
'BANG_Value4',
];
// Your data to filters
const tasks = [{
eventData: {
workflow_name: 'brand',
task_queue_name: 'BANG_Value3 and Value2 and Value3',
},
}, {
eventData: {
workflow_name: 'brand',
task_queue_name: 'Dogs loves cat',
},
}, {
eventData: {
workflow_name: 'brand',
task_queue_name: 'Dogs loves BANG_Value4',
},
}];
const brand = 'brand';
const filtered = tasks.filter(x =>
x.eventData.workflow_name === brand &&
!arrayOfValue.some(y => x.eventData.task_queue_name.includes(y))
);
console.log(filtered);
答案 1 :(得分:2)
我试图创建一个像
const VALUES_TO_SKIP = ['Value1', ...]
这样的数组,并在一行中写出indexOf
条件。
我将使用带有替换和test
的正则表达式:
let filter = tasks.filter(x =>
x.eventData.workflow_name === brand && !/Value1|_Value2|Value3|BANG_Value4/.test(x.eventData.task_queue_name)
);
实时示例:
const tasks = [
{
eventData: {
workflow_name: 'foo',
task_queue_name: 'xxx BANG_Value4 yyy',
}
},
{
eventData: {
workflow_name: 'foo',
task_queue_name: 'none of them',
}
},
{
eventData: {
workflow_name: 'bar',
task_queue_name: 'Dogs loves BANG_Value4',
}
},
{
eventData: {
workflow_name: 'foo',
task_queue_name: 'none of them again',
}
},
{
eventData: {
workflow_name: 'foo',
task_queue_name: '_Value2 yyy',
}
}
];
const brand = "foo";
let filter = tasks.filter(x =>
x.eventData.workflow_name === brand && !/Value1|_Value2|Value3|BANG_Value4/.test(x.eventData.task_queue_name)
);
console.log(filter);
.as-console-wrapper {
max-height: 100% !important;
}
答案 2 :(得分:1)
您可以只使用every
检查多个键,而使用includes
来支持indexOf:
['Value1', '_Value2', 'Value3'].every(key =>
!x.eventData.task_queue_name.includes(key))