【发布时间】:2018-08-11 04:36:02
【问题描述】:
我想编写一个函数来检查一个对象是否至少有一个包含子字符串的值。像这样的东西(伪代码):
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,因为在 bio 中找到了子字符串 'bi':'this is my bio'。 userMatches('324d, user) 同样应该返回false。但是,usermatches('blocks', user) 应该返回 false,因为子字符串只能在其中一个键中找到,而不是在值之一中。
我正在处理的对象看起来像这样(猫鼬模式):
{
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,如下面的函数。
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) 并获得一个布尔值,那就太好了。提前非常感谢!
另外,请注意,我并没有解构所有作为字符串的键。此功能的目的是根据搜索查询过滤用户,我认为让用户通过他们的 bio、id 等为其他用户搜索可能没有太大意义,而是仅通过他们的各种“名称” '。
【问题讨论】:
-
除非这些对象的某些结构可以利用,否则不可避免地必须检查每个键以查看它是否匹配。 (排除短路
true路径,如果我们在搜索早期找到匹配项) -
感谢您的回答。我将使用对象的完整结构更新答案。我确实找到了一种方法,并且效果很好(我认为),但是正如您所说,我必须单独访问这些对..
标签: javascript string object substring filtering