js 把一个不知深度的对象去重去并集,这个不知深度的对象里面包含数组,数组也要取并集。

js 把一个不知深度的对象去重去并集,这个不知深度的对象里面包含数组,数组也要取并集。

function mergeObject(obj1, obj2) {
  const result = {};

  // 取并集
  for (let key in obj1) {
    if (key in obj2) {
      const value1 = obj1[key];
      const value2 = obj2[key];

      if (Array.isArray(value1)) {
        if (Array.isArray(value2)) {
          result[key] = mergeArray(value1, value2);
        } else {
          result[key] = value1.slice();
        }
      } else if (typeof value1 === 'object' && value1 !== null) {
        if (typeof value2 === 'object' && value2 !== null) {
          result[key] = mergeObject(value1, value2);
        } else {
          result[key] = value1;
        }
      } else {
        result[key] = value2;
      }
    } else {
      result[key] = obj1[key];
    }
  }

  for (let key in obj2) {
    if (!(key in obj1)) {
      result[key] = obj2[key];
    }
  }

  return result;
}

function mergeArray(arr1, arr2) {
  const result = arr1.slice();

  for (let i = 0; i < arr2.length; i++) {
    const item = arr2[i];

    if (Array.isArray(item)) {
      result[i] = mergeArray(result[i] || [], item);
    } else if (typeof item === 'object' && item !== null) {
      result[i] = mergeObject(result[i] || {}, item);
    } else if (!result.includes(item)) {
      result.push(item);
    }
  }

  return result;
}

function uniqObject(obj) {
  const result = {};

  for (let key in obj) {
    const value = obj[key];

    if (Array.isArray(value)) {
      result[key] = uniqArray(value);
    } else if (typeof value === 'object' && value !== null) {
      result[key] = uniqObject(value);
    } else {
      result[key] = value;
    }
  }

  return result;
}

function uniqArray(arr) {
  const result = [];

  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];

    if (Array.isArray(item)) {
      result[i] = uniqArray(item);
    } else if (typeof item === 'object' && item !== null) {
      result[i] = uniqObject(item);
    } else if (!result.includes(item)) {
      result.push(item);
    }
  }

  return result;
}

你可能感兴趣的:(JS,javascript)