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 渲染中,我如何合并具有相同用户名的消息并将文本呈现在彼此之下?
不要在视图中使用它,使用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>
如果我有数组:
let messages = [
{
username: 'john',
message: 'hi'
},
{
username: 'john',
message: 'there'
},
{
username: 'bob',
message: 'hello'
},
{
username: 'john',
message: 'whats up'
}
]
如果我收到如下消息:
在 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>