vue3中写,若id相同,则把对象放到一个新数组里面,并且展示出来
时间: 2024-04-16 08:27:23 浏览: 133
在 Vue 3 中,您可以使用 Array.prototype.reduce()
方法来实现将具有相同 id 的对象放入一个新数组中。下面是一个示例代码:
// 假设原始数据是一个数组,包含多个对象
const originalArray = [
{ id: 1, name: 'Object 1' },
{ id: 2, name: 'Object 2' },
{ id: 1, name: 'Object 3' },
{ id: 3, name: 'Object 4' },
{ id: 2, name: 'Object 5' }
];
// 使用 reduce 方法将具有相同 id 的对象放入新数组
const newArray = originalArray.reduce((result, object) => {
const existingObject = result.find(item => item.id === object.id);
if (existingObject) {
existingObject.name += ', ' + object.name;
} else {
result.push({ id: object.id, name: object.name });
}
return result;
}, []);
// 在 Vue 模板中展示新数组
<template>
<div>
<div v-for="object in newArray" :key="object.id">
{{ object.name }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
newArray: newArray
}
}
}
</script>
在上面的示例中,我们使用 reduce()
方法遍历原始数组,并将具有相同 id 的对象合并为一个对象,将结果存储在 newArray
中。然后,在 Vue 模板中使用 v-for
指令遍历 newArray
,展示合并后的对象。
请注意,这只是一个示例,您可以根据您的实际需求进行调整和修改。希望对您有帮助!如果您有任何其他问题,请随时提问。
相关推荐


















