我有一个对象数组:
array = [
{ age: 5, name: foo },
{ age: 5, name: bar },
{ age: 8, name: baz }
]
我像这样遍历数组:
<div v-for="(arr, index) in array" :key="index">
<h5>age: {{ arr.age }}</h5>
<ul>
<li>{{ arr.name }}</li>
</ul>
</div>
呈现如下:
<div>
<h5>age: 5</h5>
<ul>
<li>foe</li>
</ul>
</div>
<div>
<h5>age: 5</h5>
<ul>
<li>bar</li>
</ul>
</div>
<div>
<h5>age: 8</h5>
<ul>
<li>baz</li>
</ul>
</div>
但是我想要相同年龄的数组像这样合并:
<div>
<h5>age: 5</h5>
<ul>
<li>foe</li>
<li>bar</li>
</ul>
</div>
<div>
<h5>age: 8</h5>
<ul>
<li>baz</li>
</ul>
</div>
我正在考虑制作一个单独的对象并合并数组的内容,如果年龄键/值对是相同的。我怎样才能得到这个?
试试下面的代码片段:
new Vue({
el: '#demo',
data() {
return {
array: [{age: 5, name: 'foo'}, {age: 5, name: 'bar'}, {age: 8, name: 'baz'}]
}
},
computed: {
newArr() {
const uniques = [...new Set(
this.array.map(x => JSON.stringify(((o) => ({
age: o.age,
}))(x))))
].map(JSON.parse);
this.array.forEach(a => {
let idx = uniques.findIndex(u => u.age === a.age)
if(!uniques[idx].name) uniques[idx].name = []
uniques[idx].name.push(a.name)
})
return uniques
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div v-for="(arr, index) in newArr" :key="index">
<h5>age: {{ arr.age }}</h5>
<ul>
<li v-for="(name, i) in arr.name" :key="i">{{ name }}</li>
</ul>
</div>
</div>
您可以解析您的对象以构建您喜欢的对象然后创建你的模板
array = [
{
age: 5,
name: "foo"
},
{
age: 5,
name: "bar"
},
{
age: 8,
name: "baz"
}
];
var newarr = {};
array.map((e) => {
if (!newarr[e.age]) newarr[e.age] = [];
newarr[e.age].push(e.name);
});
for (const [key, value] of Object.entries(newarr)) {
console.log(`${key}`);
for (const v of value) {
console.log(`${v}`);
}
console.log("==========================");
}