-2

If I have the array:

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

If i have messages like: Vuejs example

In vuejs rendered out how would I combine messages with the same username and render the text under each other?

svoruganti
  • 523
  • 1
  • 3
  • 25

1 Answers1

-1

Don't to it in the view, use a computed to get the data you want. You can then use <template> tags to control which elements are shown, that way you don't need to wrap the elements into a single DOM element.

Below is an example that shows a straight forward way of generating an array for the computed that can then be iterated over.

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>
Daniel
  • 34,125
  • 17
  • 102
  • 150