I have a JSON object and I want to write a function to look for the chat_userID and return the corresponding nome.
I came up with:
utenti_chat = [{
"nome": "John Doe",
"id": 5,
"email": "[email protected]",
"chat_userID": "c1f2580cad95fa0f"
},
{
"nome": "Jane Doe",
"id": 6,
"email": "[email protected]",
"chat_userID": "ed86742608dde1fe"
}
]
userConnected = utenti_chat.filter(a => a.chat_userID.find(w => w == user.userID)).map(a => a.nome);
but it returns that
a.chat_userID.find is not a function
how can I fix it?
4
Answers
You don’t need the inner
find
, becausefilter
already does the searching for you:Just use
in your
filter()
First, you use the
filter
method which won’t be that helpful here. Then, you callfind
on a variable which its type is anstring
, which has no method calledfind
so that is why you get the error.So given some input, say
userId
the way to get what you want would be,Keep in mind you should handle edge cases, mostly where could not find a matching user with the
userId
. This is why I used the(...)?.nome
expression. The?
operator stands for handling that case I described. When a matching user object won’t be found, the value ofutenti_chat.find(a => a.chat_userID === userId)
would benull
. In that case if you won’t user the?
operator you will get run time error for trying to accessnome
key of anull
.It looks like you’re trying to filter the utenti_chat array based on the condition that the chat_userID matches a specific value (user.userID). However, there’s a small mistake in your code. The chat_userID property is a string, so you don’t need to use .find() on it. Instead, you can directly compare it.
In this corrected code:
I replaced .find(w => w == user.userID) with === to directly compare chat_userID with user.userID.
The filtered array is then mapped to extract the nome property.
Make sure that user.userID is defined before using this function to avoid any potential issues.