判断两个对象数组是否完全相同

134 阅读2分钟

1. 前言

做数据操作时,偶尔需要对比两个数组对象是否相等。

2. 问题


  • 两个对象数组是否完全相等。
  • 两个对象数组是否某个对象值相等。

最后返回相同部分,组成一个新的数组。

3. 解答

1)两个对象数组是否完全相等

Map中的has

Map示例 const m = new Map([['name', '张三']]);

注意这个方法是比较全等,若数组中的对象值不同或者某一项对象个数对不上,则都不算全等

数组中的对象值,顺序不同不影响比较结果。

// 获得1和2中相同的数据
getSameValue() {
  const findEqualObjects = (arr1, arr2) => {
    // 将第一个数组的对象转换为键值对,以对象的JSON字符串作为键
    const map = new Map(arr1.map(obj => [JSON.stringify(obj), obj]));
    // 遍历第二个数组,根据map的has方法:检查对象是否在map中
    const equalObjects = arr2.filter(obj => map.has(JSON.stringify(obj)));
    // 返回完全相等的对象数组
    return equalObjects;
  }
  // 示例数组
  const array1 = [
    { value: '0', label: '加班' },
    { value: '1', label: '上网', key: '2' },
  ];
  const array2 = [
    { label: '加班', value: '0' },
    { value: '1', label: '上网' },
    { value: '1', label: '睡觉' },
  ];
  // 调用函数并打印结果
  const common = findEqualObjects(array1, array2);
  console.log(common);
},

结果:

image.png

2)两个对象数组是否某个对象值相等

find方法:对比value值,返回值相同的对象。

// 获得1和2中相同的数据
getSameValue() {
  const findEqualObjects = (arr1, arr2) => {
    var resultArr = [];
    // 根据value对比得出两个数组相同部分
    arr2.forEach(item => {
      resultArr.push(arr1.find(_item => _item.value === item.value));
    })
    return resultArr
  }
  // 示例数组
  const array1 = [
    { value: '0', label: '加班' },
    { value: '1', label: '上网', key: '2' },
  ];
  const array2 = [
    { label: '加班', value: '0' },
    { value: '1', label: '上网' },
    { value: '1', label: '睡觉' },
  ];
  // 调用函数并打印结果
  const common = findEqualObjects(array1, array2);
  console.log(common);
},

结果:

image.png

4. 后记

map数据结构还需要加深学习和运用。

5. 引用来源

作者:L-weixin-45629194

文章链接:blog.csdn.net/weixin_4562…
违规请联系删除,plz。