比较两个对象中发生改变的值 - davy-gan/web GitHub Wiki

import _ from 'lodash';
/**
 * @example
 * const compareData = getComparedObj(newObj, oldObj)
 * 直接使用
 * comapreData.xx = {
 *  val: 123,
 *  isChange: true,
 *  oldVal: 234
 * }
 * @param {object} newObj 新数据
 * @param {oblect} oldObj 旧数据
 * JSON.parse(JSON.stringify(compareData))
 */
export function getComparedObj(newObj = {}, oldObj = {}) {
  return new Proxy(newObj, {
    get(target, key, receiver) {
      const newValue = Reflect.get(target, key, receiver);
      const oldValue = Reflect.get(oldObj, key, receiver);
      if (_.isArray(newValue)) {
        return newValue.map((t, i) => getComparedObj(t, _.get(oldValue, i)));
      }
      if (_.isObject(newValue)) {
        return getComparedObj(newValue, oldValue);
      }
      const isChange = newValue !== oldValue;
      const result = {
        val: newValue,
        isChange,
      };
      if (isChange) {
        result.oldVal = oldValue;
      }
      return result;
    },
  });
}