So im building an app mock up , upon sending a message I need to notify all the participants of the chat that they have an unread message, My participant type has a field called "unread" which is an array of objects like such
unread:[
{chatId:'13213', msgs:3},
{chatId:'132546', msgs:1}
];
chat id references to a unique conversation, and msgs number shows new messages sent , the length of msgs array is the number of unread msgs you have , what I want to do is , when a new msg is sent I want to loop through the unread array and
condition one Array is completely empty :
- add an object to it
condition two array already has objects, then find the one that has the same chatId as the one I will pass in the function and increase the message count
condition three, array already has objects but not with the chatId I provided, in which case create a new object and add it to an existing array.
any ideas on how I can go about this?
I tried doing the following but it doesn't work
emp.unread.length < 1
? [{ chatId: chatId, unread: 1 }]
: emp.unread.map((cht) => {
if (cht.chatId === chatId) {
return {
...emp.unread,
chatId: chatId,
unread: cht.unread 1,
};
} else {
return { ...emp.unread, chatId: chatId, unread: 1 };
}
}),
CodePudding user response:
You can try using the if condition as below:
You can use filter/find to complete you tasks normally.There could still be other less resource consuming way but this way you will get your task done.
if(unread.length == 0 ){
//pushing the object
}else{
if(chechExistingChat(chatid)){
addOnExistingChat(chatId)
}
else{
//unread.push(new object)
}
}
function checkExistingChat(chatId){
let sameChatArray = unread.filter((item)=>{
return item.chatId == chatId
})
return !!sameChatArray.length
}
function addOnExistingChat(chatId){
let finalArray = unread.map((item)=>{
if(item.chatId == chatId){
return {...item,msgs:item.msgs 1}
}
return item
})
return finalArray
}