首页 > 解决方案 > 如何聚合 JSON 以显示每个相同值的计数

问题描述

我从我的服务器响应中获得了以下数据:

var data = [
    {
        project: {
            name: "KB",
            $type: "Project"
        }
    },
    {
        project: {
            name: "Test",
            $type: "Project"
        }
    },
    {
        project: {
            name: "Test",
            $type: "Project"
        }
    },
    {
        project: {
            name: "KB",
            $type: "Project"
        }
    },
    {
        project: {
            name: "Test",
            $type: "Project"
        }
    },
    {
        project: {
            name: "Test",
            $type: "Project"
        }
    }
];

我需要为以下步骤准备数据。理想情况下,我需要得到以下输出:

var aggregatedData = [
    {
        projectName: "KB",
        count: 2
    },{
        projectName: "Test",
        count: 4
    },
];

可能吗?如果是这样,使用 jQuery 实现这一点的最佳方法是什么?

标签: javascriptjquery

解决方案


你可以这样做 -

var data = [{
    project: {
      name: "KB",
      $type: "Project"
    }
  },
  {
    project: {
      name: "Test",
      $type: "Project"
    }
  },
  {
    project: {
      name: "Test",
      $type: "Project"
    }
  },
  {
    project: {
      name: "KB",
      $type: "Project"
    }
  },
  {
    project: {
      name: "Test",
      $type: "Project"
    }
  },
  {
    project: {
      name: "Test",
      $type: "Project"
    }
  }
];

var hashMap = {}

data.map(element => {
  // if the key(name) is inserted in our hashmap, just increment the count
  // if the key isn't present, then just assign the count of that key(name) as 1 and increment next time onwards
  hashMap[element.project.name] = hashMap[element.project.name] + 1 || 1;
});

// our count for each name is ready...just getting the result ready in our desired format
var aggregatedData =
  Object.keys(hashMap).map(element =>
    ({
      projectName: element,
      count: hashMap[element]
    })
  )
// And done ... :)
console.log(aggregatedData);

我们在上述方法中所做的是创建一个变量,该变量将充当 out hashmap。它将遍历data数组,并且对于数组中的每个元素data,我们正在计算每个唯一名称的出现次数。

最后,我们正在迭代创建的 hashmap 并使用存储在 hashmap 中的键值对(它们只是出现次数对的名称),并使用它以我们所需的格式获取聚合数据。


推荐阅读