Javascript使用includes()检查带有对象键的数组,但不检查整个单词



我有以下代码。CCD_ 1对象和CCD_ 2字数组。

如果body关键字包含sensitive单词中的任何单词,则应返回true。

const body = {
name: "",
email: "",
otpp: ""
}
const sensitiveWords = ["password", "pin", "otp"]
const isSensitive = sensitiveWords.some(el => Object.keys(body).map(name => name.toLowerCase()).includes(el)) || false
console.log(isSensitive);
// returns: false
// expected result: true

但正如你所看到的,单词otp在敏感词中,但它与otpp不匹配。我想是因为它在寻找全字符串匹配。

我需要上面的函数返回true,因为密钥在otpp中包含otp

谢谢。

您正在寻找

const containsSensitive = sensitiveWords.some(el =>
Object.keys(body).some(name =>
//                  ^^^^
name.toLowerCase().includes(el)
//                     ^^^^^^^^ string search
)
)

我提供了一个使用双some()进行的解决方案

const body = {
name: "",
email: "",
otpp: ""
}
let sensitiveWords = ["password", "pin", "otp"]
const isSensitive = (body,words) => Object.keys(body).map(n => n.toLowerCase()).some(d1 => words.some(d2 => d1.includes(d2)))
console.log(isSensitive(body,sensitiveWords)) // true
sensitiveWords = ["password", "pin", "otps"]
console.log(isSensitive(body,sensitiveWords)) // false

您可以尝试使用带有不区分大小写标志(body0(的regex。这可能比使用两个嵌套循环更具性能。

const body = {
name: '',
email: '',
password: ''
}
const sensitiveWords = ['password', 'pin', 'otp']
const sensitiveWordsRegex = new RegExp(sensitiveWords.join('|'), 'i')
const keys = Object.keys(body)
const hasSensitiveWord = keys.some(key => sensitiveWordsRegex.test(key))
console.log(hasSensitiveWord)

Bergi的答案是最好的。我只是想分享我的工作,我意识到我让它变得如此复杂。

顺便说一句,解释你的代码为什么不起作用是因为:

  • 正在数组中搜索单词(body object keys数组Object.keys(body)(--此将不起作用,因为您基本上是在比较字符串而不是在其中搜索子字符串

您需要做的是在字符串中搜索子字符串

  • 您必须遍历body键,并在每个键中搜索一个子字符串-->string.includes('string)

JsFiddle链接

/* 
** The answer of Bergi is the best one but just want to share what I worked on 
** (https://stackoverflow.com/a/74150607/8414995) 
** if you want it the hard way
*/

// Check if strings from an array matches a key (substring or whole word) of an object
const body = {
name: '', email: '', otpp: '',
}
// list of words to be searched in the body keys
const sensitiveWords = ['password', 'pin', 'otp']
// list down the keys first maybe to make the code clearer?
const bodyKeys = Object.keys(body)
// search through each word from sensitiveWords
const hasData = sensitiveWords.some(el => {
// iterate through each word from bodyKeys and check if the sensitive word matches a substring of the body key. Filter only the true values
const result = bodyKeys.map(bEl => {
// return true if it matches anything
if (bEl.includes(el)) {
return true
}
}).filter(el => el == true)

// the result will be in array form so let's just check if the length > 0
return !!result.length
})
console.log(hasData) 

// Check if strings from an array matches a key (substring or whole word) of an object

我会尝试json字符串化整个主体,并拆分为单词,然后在上搜索

最新更新