亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

js如何檢查數組中的兩個對象值是否在一起

js如何檢查數組中的兩個對象值是否在一起

湖上湖 2023-05-25 17:08:14
如果我有數組:let messages = [  {    username: 'john',    message: 'hi'  },  {    username: 'john',    message: 'there'  },  {    username: 'bob',    message: 'hello'  },  {    username: 'john',    message: 'whats up'  }]如果我有這樣的消息:在 vuejs 渲染中,我將如何組合具有相同用戶名的消息并將文本呈現在彼此之下?
查看完整描述

1 回答

?
拉風的咖菲貓

TA貢獻1995條經驗 獲得超2個贊

不要在視圖中使用它,使用 acomputed來獲取您想要的數據。然后您可以使用<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>


查看完整回答
反對 回復 2023-05-25
  • 1 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號