'Update nested array ES6, JavaScript
I have the following array of objects:
[{
idChatPublic: "1",
message: "hello",
chatLike: [{
id: "1",
idChatPublic: "1"
}]
}]
What I want is simply add a new object into chatLike array. Here is my attempt, but it doesn't seem to be working whats wrong with this piece of code?
async function sendLike(messageId: string) {
const newLike = {
idChatPublic: messageId,
}
mutateMessages(
(data) => {
console.log(data) // returns the array I want to update
data.map((message) => {
if (message.idChatPublic === messageId) {
console.log(message.chatLike) // returns the array inside the object I want to update
return {
...message,
chatLike: [...message.chatLike, newLike]
}
} else {
return message
}
})
}
)
}
Solution 1:[1]
const data = [
{
idChatPublic: "1",
message: "hello",
chatLike: [
{
id: "1",
idChatPublic: "1",
},
],
},
];
function updateChatLike() {
return data.map((d) => {
return {
...d,
chatLike: [
...d.chatLike,
{
id: 2,
idChatPublic: "2",
},
],
};
});
}
console.log(JSON.stringify(updateChatLike(), null, 4));
I have used JSON.stringify() to log complete nested object
Output
[
{
"idChatPublic": "1",
"message": "hello",
"chatLike": [
{
"id": "1",
"idChatPublic": "1"
},
{
"id": 2,
"idChatPublic": "2"
}
]
}
]
Solution 2:[2]
You don't need map(). I think you can do that like this:
async function sendLike(messageId: string) {
const newLike = {
idChatPublic: messageId,
};
mutateMessages((data) => {
data.forEach((message) => {
if (message.idChatPublic === messageId) {
message.chatLike.push(newLike);
}
}
});
}
Loop throw your objects array with forEach() and if the id will match you can update chatLike array with push() to add a new newLike object.
Solution 3:[3]
Map is not necessary here in your case.
Try this.
const data = [{
idChatPublic: "1",
message: "hello",
chatLike: [{
id: "1",
idChatPublic: "1"
}]
}];
console.log("before " , data);
sendLike(1);
console.log("after " , data);
function sendLike(messageId) {
const newLike = {
idChatPublic: messageId,
}
// mutateMessages((data) => {
data.forEach((message) => {
//console.log(message.idChatPublic);
if (message.idChatPublic == messageId) {
message.chatLike.push(newLike);
}
});
//});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harsh Mangalam |
| Solution 2 | |
| Solution 3 | Mahesh Bongani |
