vue 将数组2中的数据在数组1中查找下,如果没有则添加,否则不添加

发布于:2024-03-29 ⋅ 阅读:(81) ⋅ 点赞:(0)

vue 将数组2中的数据在数组1中查找下,如果没有则添加,否则不添加

<template>
  <!-- 这里是你的模板内容 -->
</template>

<script>
export default {
  data() {
    return {
      array1: [1, 2, 3, 4],
      array2: [3, 5, 6, 7],
    };
  },
  methods: {
    mergeUniqueItems() {
      // 创建一个新数组来避免直接修改原数组导致的Vue不能检测到变化的问题
      const newArray = [...this.array1];

      this.array2.forEach(item => {
        // 使用includes方法判断item是否在原数组中存在
        if (!newArray.includes(item)) {
          // 如果不存在,则push进新数组
          newArray.push(item);
        }
      });

      // 更新array1的值
      this.array1 = newArray;
    },
  },
  created() {
    // 在组件创建后立即执行合并操作
    this.mergeUniqueItems();
  },
};
</script>

上述代码中,mergeUniqueItems 方法负责遍历 array2 中的每一项,通过 Array.prototype.includes() 检查 array1 是否已经包含了当前项。如果没包含,则将当前项添加到新建的 newArray 中。最后,将 newArray 赋值给 array1,以更新视图。

在真实的应用场景中,你可能希望在某个事件触发时(比如用户点击按钮)才执行这个合并操作,而不是在 created 生命周期钩子中执行。只需相应地调整调用 mergeUniqueItems 方法的位置即可。

例子:

array1:[{id:1,name:'你好'},{id:2,name:'你好2'}];
array2:[{id:3,name:'哈哈'},{id:2,name:'你好2'}];

将数组array2中的数据添加到array1中,且不重复

在Vue中处理这个问题,我们需要根据对象的id进行去重,因为这里是对象数组,而不仅仅是数值数组。下面是如何实现这个需求的示例代码:

<template>
  <!-- 这里是你的模板内容 -->
</template>

<script>
export default {
  data() {
    return {
      array1: [{ id: 1, name: '你好' }, { id: 2, name: '你好2' }],
      array2: [{ id: 3, name: '哈哈' }, { id: 2, name: '你好2' }],
    };
  },
  methods: {
    mergeUniqueObjects() {
      // 使用Set结合JSON.stringify实现对象数组去重
      const idsInArray1 = new Set(this.array1.map(item => JSON.stringify(item)));

      // 遍历array2,将不在array1中的对象添加到array1
      this.array2.forEach(item => {
        const stringifiedItem = JSON.stringify(item);
        if (!idsInArray1.has(stringifiedItem)) {
          this.array1.push(item);
          idsInArray1.add(stringifiedItem);
        }
      });
    },
  },
  created() {
    this.mergeUniqueObjects();
  },
};
</script>


网站公告

今日签到

点亮在社区的每一天
去签到