适用于 echarts 的合并配置工具

74 阅读1分钟

源码

const mergeOption = (old = {}, to = {}) => {
  const mergeObj = {}
  // 去重
  const keys = new Set([...Object.keys(old), ...Object.keys(to)])
  keys.forEach(key => {
    const oldVal = old[key]
    const toVal = to[key]

    // 如果两个对象都有某个 key
    if ({}.hasOwnProperty.call(old, key) && {}.hasOwnProperty.call(to, key)) {
      // 该 key 的 value 是对象 则递归合并
      if (typeof toVal === 'object' && toVal !== null && !Array.isArray(toVal)) {
        mergeObj[key] = mergeOption(oldVal, toVal)
      } else {
        mergeObj[key] = toVal
      }
    } else {
      mergeObj[key] = oldVal || toVal
    }
  });

  return mergeObj;
}

和 assign与 lodash的merge的不同

  1. 不会改变原对象

  2. 在遇到值是 Array 的情况下,新值会直接覆盖旧值

使用场景

项目折线图公共配置

const lineChartBaseOptions = {
  tooltip: {
    trigger: 'axis'
  },
  title: {
    text: '',
    textStyle: {
      fontFamily: 'Microsoft YaHei',
    },
    itemGap: 10,
  },
  grid: {
    top: 48,
    left: 26,
    bottom: 16,
    right: 26,
    containLabel: true
  },
}

然后在制作某一个图表时,会有这个图表特有的配置

const line1Options = {
  title: {
    text: 'hello title',
  },
  grid: {
    left: 0,
  },
  xAxis: {
    data: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
  }
}

此时将两个配置合并

const options = mergeOption(lineChartBaseOptions, line1Options)
chart.setOption(options)

合并后的配置为

{
  tooltip: {
    trigger: 'axis'
  },
  title: {
    text: 'hello title', // 合并部分
    textStyle: {
      fontFamily: 'Microsoft YaHei',
    },
    itemGap: 10,
  },
  grid: {
    top: 48,
    left: 0, // 合并部分
    bottom: 16,
    right: 26,
    containLabel: true
  },
  xAxis: { // 合并部分
    data: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
  }
}