将新消息添加到已建立索引的对象

时间:2018-10-18 00:24:30

标签: javascript vue.js socket.io

我创建了一个Messenger,它将来自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));
},

2 个答案:

答案 0 :(得分:1)

// transform the object into a correctly indexed array
let messagesArr = Array.from(Object.keys(this.messages).sort((a, b) => parseInt(a) < parseInt(b)), i => this.messages[i]);

// from here, you can add the message pretty easily.
messagesArr.unshift(data.message[0]);

// finally, just transform it back into an object (if you really have to)
const temp = {};
messagesArr.forEach((value, index) => temp["" + index] = value);
this.messages = temp;

答案 1 :(得分:1)

如果我的理解正确,您想将messages视为可以移入的数组。因此,您将其转换为数组,移至其上,然后将其转换回。这与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>