js如何检查数组中的两个对象值是否在一起

如果我有数组:


let messages = [

  {

    username: 'john',

    message: 'hi'

  },

  {

    username: 'john',

    message: 'there'

  },

  {

    username: 'bob',

    message: 'hello'

  },

  {

    username: 'john',

    message: 'whats up'

  }

]

如果我有这样的消息:

http://img1.mukewang.com/646f259100016c1a02170372.jpg

在 vuejs 渲染中,我将如何组合具有相同用户名的消息并将文本呈现在彼此之下?



湖上湖
浏览 95回答 1
1回答

拉风的咖菲猫

不要在视图中使用它,使用 acomputed来获取您想要的数据。然后您可以使用<template>标签来控制显示哪些元素,这样您就不需要将元素包装到单个 DOM 元素中。computed下面是一个示例,它显示了为然后可以迭代的数组生成数组的直接方法。Vue.createApp({&nbsp; data() {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; messages: [{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username: 'john',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: 'hi'&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username: 'john',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: 'there'&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username: 'bob',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: 'hello'&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username: 'john',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: 'whats up'&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; }&nbsp; },&nbsp; computed: {&nbsp; &nbsp; byUser() {&nbsp; &nbsp; &nbsp; const arr = [];&nbsp; &nbsp; &nbsp; let tempName = null;&nbsp; &nbsp; &nbsp; let tempGroup = {}&nbsp; &nbsp; &nbsp; this.messages.forEach(m => {&nbsp; &nbsp; &nbsp; &nbsp; if (tempName !== m.username) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tempGroup = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; username: m.username,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; messages: []&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arr.push(tempGroup);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; tempGroup.messages.push(m.message);&nbsp; &nbsp; &nbsp; &nbsp; tempName = m.username;&nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; return arr;&nbsp; &nbsp; }&nbsp; }}).mount("#app")<script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script><div id="app" class="container">&nbsp; <template v-for="(m, i) in byUser">&nbsp; &nbsp; <h2>&nbsp; &nbsp; &nbsp; {{ m.username }}&nbsp; &nbsp; </h2>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <p v-for="message in m.messages">&nbsp; &nbsp; &nbsp; {{ message }}&nbsp; &nbsp; </p>&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <hr>&nbsp; </template></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript