Talk is cheap. Show me your code

JavaScript 一维数组转二维数组

问题描述:

有如下结构的一维数组:

const list = [
    {grade: '小学', city: '北京', count: 18},
    {grade: '小学', city: '上海', count: 12},
    {grade: '小学', city: '杭州', count: 19},
    {grade: '小学', city: '深圳', count: 10},
    {grade: '初中', city: '北京', count: 18},
    {grade: '初中', city: '上海', count: 12},
    {grade: '初中', city: '杭州', count: 19},
    {grade: '初中', city: '深圳', count: 10},
    {grade: '高中', city: '北京', count: 18},
    {grade: '高中', city: '上海', count: 12},
    {grade: '高中', city: '杭州', count: 19},
    {grade: '高中', city: '深圳', count: 10},
    {grade: '大学', city: '北京', count: 18},
    {grade: '大学', city: '上海', count: 12},
    {grade: '大学', city: '杭州', count: 19},
    {grade: '大学', city: '深圳', count: 10},
]

需要处理为二维数组,其中第一维是 grade,第二维是 city:

cosnt res = [
  {
    name: "小学", value:
    [
      {name: "北京", value: 18}
      {name: "上海", value: 12}
      {name: "杭州", value: 19}
      {name: "深圳", value: 10}
    ]
  }
  {
    name: "初中", value:
    [
      {name: "北京", value: 18}
      {name: "上海", value: 12}
      {name: "杭州", value: 19}
      {name: "深圳", value: 10}
    ]
  }
  {
    name: "高中", value: 
    [
      {name: "北京", value: 18}
      {name: "上海", value: 12}
      {name: "杭州", value: 19}
      {name: "深圳", value: 10}
    ]
  }
  {
    name: "大学", value: 
    [
      {name: "北京", value: 18}
      {name: "上海", value: 12}
      {name: "杭州", value: 19}
      {name: "深圳", value: 10}
    ]
  }
]

 

解决方案:

/**
 * 将一维数组处理为二维数组
 * @param {Array} list 需要处理的一维数组
 * @param {Object} extra 包含 nameKey 和 valueKey
 * @param {Array} nameKey 长度为二的数组,依序为 name 取值
 * @param {String} valueKey value 取值的键
 * @returns 
 */
function convertOneDimArray(list, extra) {
  const { nameKey, valueKey } = extra || {};

  if (!nameKey || nameKey.length < 2 || !Array.isArray(list)) {
    return null;
  }

  const [name1, name2] = nameKey;
  const xMap = new Map();

  list.forEach((item) => {
    const x = item[name1];
    const y = {
      name: item[name2],
      value: item[valueKey],
    }
    const xValue = xMap.get(x);
    if (!xValue) {
      xMap.set(x, {
        name: x,
        value: [y],
      });
    } else {
      xValue.value.push(y)
    }
  });

  return [...xMap.values()];
}

 

 

posted @ 2021-07-02 09:39  Wise.Wrong  阅读(2199)  评论(0编辑  收藏  举报