繁体   English   中英

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

[英]js how to check two objects values in an array are together

如果我有数组:

let messages = [
  {
    username: 'john',
    message: 'hi'
  },
  {
    username: 'john',
    message: 'there'
  },
  {
    username: 'bob',
    message: 'hello'
  },
  {
    username: 'john',
    message: 'whats up'
  }
]

如果我有这样的消息: Vuejs 示例

在 vuejs 中渲染出如何将具有相同用户名的消息组合在一起并在彼此下方渲染文本?

不要在视图中使用它,使用computed来获取您想要的数据。 然后您可以使用<template>标签来控制显示哪些元素,这样您就不需要将元素包装到单个 DOM 元素中。

下面是一个示例,它显示了为computed生成数组的直接方法,然后可以对其进行迭代。

 Vue.createApp({ data() { return { messages: [{ username: 'john', message: 'hi' }, { username: 'john', message: 'there' }, { username: 'bob', message: 'hello' }, { username: 'john', message: 'whats up' } ] } }, computed: { byUser() { const arr = []; let tempName = null; let tempGroup = {} this.messages.forEach(m => { if (tempName !== m.username) { tempGroup = { username: m.username, messages: [] } arr.push(tempGroup); } tempGroup.messages.push(m.message); tempName = m.username; }) return arr; } } }).mount("#app")
 <script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script> <div id="app" class="container"> <template v-for="(m, i) in byUser"> <h2> {{ m.username }} </h2> <p v-for="message in m.messages"> {{ message }} </p> <hr> </template> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM