I want to write a function that checks if an object has at least one value containing a substring. Something like this (pseudo-code):
const userMatchesText = (text, user) => user.includes(text);
The full structure of my objects (
So, for a user like the following:
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)
should return true
because the substring 'bi' is found in the bio: 'this is my bi
o'. userMatches('324d, user) should likewise return false
. usermatches('blocks', user)
should, however, return false
because the substring is only found in one of the keys, not one of the values.
The objects I'm working it look like this (the Mongoose Schema):
{
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
}
}
The best way of doing this I've found so far is destructuring all the keys that are strings off the object, and then using map
and includes
, like the function below.
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);
}
});
};
This is, however, really annoying (and probably terribly inefficient, too), as the objects I'm working with are really large. It'd be really nice if i could just call userMatchesText(text, user)
and get a Boolean value. Thanks a lot in advance!
Also, note I am not destructuring off all the keys that are Strings. The purpose of this function is to filter users based on a search query, and I figured it perhaps doesn't make too much sense to let users serch for other users by their bio, id etc. but rather, only by their various 'names'.