[英]Update nested array ES6, JavaScript
我有以下對象數組:
[{
idChatPublic: "1",
message: "hello",
chatLike: [{
id: "1",
idChatPublic: "1"
}]
}]
我想要的只是將一個新的 object 添加到 chatLike 數組中。 這是我的嘗試,但似乎沒有用 這段代碼有什么問題嗎?
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
}
})
}
)
}
map() 方法創建一個新數組,其中填充了對調用數組中每個元素調用提供的 function 的結果。
可能,您必須使用新數組創建 const 並將其返回:
const newData = 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
}
});
return newData;
你不需要map()
。 我認為你可以這樣做:
async function sendLike(messageId: string) { const newLike = { idChatPublic: messageId, }; mutateMessages((data) => { data.forEach((message) => { if (message.idChatPublic === messageId) { message.chatLike.push(newLike); } } }); }
使用forEach()
循環拋出您的對象數組,如果 id 匹配,您可以使用push()
更新chatLike
數組以添加新的newLike
object。
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));
我已經使用 JSON.stringify() 來記錄完整的嵌套 object
Output
[
{
"idChatPublic": "1",
"message": "hello",
"chatLike": [
{
"id": "1",
"idChatPublic": "1"
},
{
"id": 2,
"idChatPublic": "2"
}
]
}
]
Map 在您的情況下不是必需的。
嘗試這個。
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); } }); //}); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.