Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue数组对象去重

作者:邪天血战   发布日期:2025-05-11   浏览:107

// 示例代码:Vue 数组对象去重

// 假设我们有一个包含多个对象的数组,每个对象都有一个唯一的 id 属性
const array = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 1, name: 'Alice' }, // 重复项
  { id: 3, name: 'Charlie' }
];

// 使用 Map 来去重
function uniqueArray(array, key) {
  const map = new Map();
  const unique = array.filter(item => {
    if (!map.has(item[key])) {
      map.set(item[key], true); // 存储唯一值
      return true;
    }
    return false;
  });
  return unique;
}

// 调用函数并输出结果
const result = uniqueArray(array, 'id');
console.log(result);
// 输出: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' } ]

// 解释:
// 1. 我们定义了一个 `uniqueArray` 函数,该函数接收两个参数:要处理的数组和用于比较的键(例如 'id')。
// 2. 使用 `Map` 数据结构来存储已经遇到的键值,确保不会重复。
// 3. `filter` 方法遍历数组,并只保留那些在 `Map` 中尚未存在的项。
// 4. 最终返回去重后的数组。

上一篇:vue 监听点击整个页面事件

下一篇:vue cors

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站