gpt4 book ai didi

javascript - 如何从数组中获取最后一个对象并在javascript中保持父数组相同

转载 作者:行者123 更新时间:2023-12-02 01:46:03 25 4
gpt4 key购买 nike

嗨,我有一个带有消息键的数组,其中有多个对象,我想删除消息数组中除最后一个对象之外的所有对象

我有下面的示例数组:

const array = [
{
messages: [
{ content: "abc", id: "message01" },
{ content: "def", id: "message02" },
{ content: "ghi", id: "message03" }
],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [
{ content: "hello", id: "message01" },
{ content: "hi", id: "message02" },
{ content: "How are you", id: "message03" }
],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];

下面是我的异常(exception)数组:

const expectedArray = [
{
messages: [{ content: "ghi", id: "message03" }],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [{ content: "How are you", id: "message03" }],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];

最佳答案

这是你想要的吗?

编辑:此代码将循环数组,并将 messages 设置为 messages[0] 这是最后一个对象

const array = [
{
messages: [
{
content: "abc",
id: "message01"
},
{
content: "def",
id: "message02"
},
{
content: "ghi",
id: "message03"
}
],
user: "user 1",
participants: ["user1", "user2"],
id: "chat01"
},
{
messages: [
{
content: "hello",
id: "message01"
},
{
content: "hi",
id: "message02"
},
{
content: "How are you",
id: "message03"
}
],
user: "user 2",
participants: ["user1", "user2"],
id: "chat02"
}
];

array.forEach(e=>{
e.messages = e.messages[e.messages.length - 1]
})

console.log(array)

关于javascript - 如何从数组中获取最后一个对象并在javascript中保持父数组相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70879831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com