我希望编写一个函数,检查一个对象中是否至少有一个值包含子字符串。类似于这样的伪代码:
const userMatchesText = (text, user) => user.includes(text);
我的对象的完整结构(因此,对于像以下用户一样的用户:
const user = {
id: '123abc',
info: {
age: 12,
bio: 'This is my bio'
},
social: {
chatName: 'Chris',
friends: ['friend1', 'other friend'],
blocks: ['Creep']
}
//Etc. The objects I'm working with contain nested objects and arrays, etc.
}
userMatches('bi', user)
应该返回 true
,因为子字符串 'bi' 在个人资料中被发现:'this is my bi
o'。userMatches('324d, user) 同样应返回false
。然而,usermatches('blocks', user)
应该返回false
,因为该子字符串只在键之一中找到,而不在任何一个值中。
我正在处理的对象看起来像这样(Mongoose模式):
{
account : {
dateOfCreation : Number
},
social : {
chatName : String,
friends : [ { type: String } ],
blocks : [ { type: String } ],
sentRequests : [ { type: String } ],
recievedRequests : [ { type: String } ],
threads : [ { type: String } ]
},
info : {
age : Number,
bio : String,
displayName : String,
profilePicture : String,
subjects : {
tutor : [
{
subject : String,
level : String
}
],
student : [
{
subject : String,
level : String
}
]
}
},
facebook : {
id : String,
firstName : String,
middleName : String,
fullName : String,
lastName : String
}
}
到目前为止,我发现最好的方法是从对象中解构出所有键都是字符串的部分,然后使用map
和includes
,如下面的函数。
到目前为止,我发现最好的方法是从对象中解构出所有键都是字符串的部分,然后使用map
和includes
,如下面的函数。
const doesUserMatchText = (user, text) => {
const { social: { chatName }, info: { displayName }, facebook: { firstName, middleName, lastName } } = user;
const possibleMatches = [ chatName, displayName, firstName, middleName, lastName ];
let match = false;
possibleMatches.map(possibleMatch => {
if (possibleMatch.includes(text)) {
return (match = true);
}
});
};
然而,这确实很烦人(也可能非常低效),因为我正在处理的对象非常大。如果我可以调用 userMatchesText(text, user)
并获得布尔值就太好了。非常感谢您的帮助!
另外,请注意我没有解构所有字符串键。此函数的目的是根据搜索查询过滤用户,并且我认为让用户通过其生物、ID等搜索其他用户可能没有太多意义,而只应通过其各种“名称”进行搜索。