gpt4 book ai didi

javascript - 将新消息添加到已索引的对象

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

我创建了一个信使,将来自 api 的最后五条消息存储在索引对象中:

data: function() {
return {
messages: {
"0":{
"id":65,
"body":"Hopefully last message",
},
"1":{
"id":64,
"body":"Another message",
},
"2":{
"id":63,
"body":"This work work?",
},
"3":{
"id":62,
"body":"Yoo",
},
"4":{
"id":61,
"body":"Hey again",
}
}
}
},

我正在使用 socket.io 来获取发送的最后一条消息,我想做的是将发送的最后一条消息推送到索引对象 this.messages 并移动索引,以便消息套接字接收到的是“0”索引对象。

mounted() {
console.log("message mounted");

let socket = io(`http://localhost:3000`);
this.getOldMessages(this.conversationPath);

socket.on('message', function (data) {

data.message[0]

//Shift data.message[0] into this.message object indexed as "0"

}.bind(this));
},

最佳答案

如果我理解正确的话,您希望将消息视为一个可以取消移位的数组。因此,您将其转换为数组,取消移位,然后将其转换回来。这与 puddi 给出的答案相同,但您似乎对他的解决方案生成的消息顺序有疑问。我无法从您的评论中看出您是否期望它会做一些与普通数组unshift不同的事情,或者他是否一些奇怪的事情。

new Vue({
el: '#app',
data() {
return {
messages: {
"0": {
"id": 65,
"body": "Hopefully last message",
},
"1": {
"id": 64,
"body": "Another message",
},
"2": {
"id": 63,
"body": "This work work?",
},
"3": {
"id": 62,
"body": "Yoo",
},
"4": {
"id": 61,
"body": "Hey again",
}
}
}
},
methods: {
unshift(message) {
const arr = [];
const result = {};

// Like Object.keys, loop through keys of object
Reflect.ownKeys(this.messages).forEach((k) => {
// Assign to corresponding array element
arr[k] = this.messages[k];
});
// Put the message on the front of the array
arr.unshift(message);
// Copy array values and indexes into result object
arr.forEach((v, i) => {
result[i] = v;
});
return result;
}
},
mounted() {
// Put a new message on the front of messages
console.log("message mounted");
const newMessage = {
id: 66,
body: 'PS: I love you'
};
this.messages = this.unshift(newMessage);
console.log("Messages:", JSON.stringify(this.messages));
}
});
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app"></div>

关于javascript - 将新消息添加到已索引的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52865306/

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