Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ember.js/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js NodeJS在JSON中迭代城市,返回每个城市的城市和用户_Node.js_Json_Object - Fatal编程技术网

Node.js NodeJS在JSON中迭代城市,返回每个城市的城市和用户

Node.js NodeJS在JSON中迭代城市,返回每个城市的城市和用户,node.js,json,object,Node.js,Json,Object,下面是一个JSON对象的代码片段,其中包含3500条记录 [ { “use:firstName”:“Bob”, “使用:姓氏”:“史密斯”, “用途:类别ID”:36, “用途:公司”:“BobSmith”, “使用:webExId”:“Bob。Smith@email.com", “用途:地址”:{ “com:addressType”:“个人”, “com:city”:“US-TX”, “com:国家”:1 } }, { “用途:名字”:“简”, “使用:姓氏”:“Doe”, “用途:类别ID”

下面是一个JSON对象的代码片段,其中包含3500条记录

[
{
“use:firstName”:“Bob”,
“使用:姓氏”:“史密斯”,
“用途:类别ID”:36,
“用途:公司”:“BobSmith”,
“使用:webExId”:“Bob。Smith@email.com",
“用途:地址”:{
“com:addressType”:“个人”,
“com:city”:“US-TX”,
“com:国家”:1
}
},
{
“用途:名字”:“简”,
“使用:姓氏”:“Doe”,
“用途:类别ID”:36,
“使用:webExId”:“简。Doe@email.com",
“用途:地址”:{
“com:addressType”:“个人”,
“com:city”:“US-CA”,
“com:国家”:“1_1”
}
}
{
“使用:名字”:“山姆”,
“use:lastName”:“Sneed”,
“用途:类别ID”:36,
“使用:webExId”:“Sam。Sneed@email.com",
“用途:地址”:{
“com:addressType”:“个人”,
“com:city”:“US-CA”,
“com:国家”:“1_1”
}
}
]
我正在使用NodeJS,我一直在寻找最佳方法: 1.迭代通过
['use:address']['com:city'
绘制并识别所有城市。(在上面的示例中,我在提供的三个记录中有两个:US-TXUS-CA) 2.然后确定与每个城市匹配的记录数(在上面的示例中,我将使用US-TX:1和US-CA:2)

我仅有的代码是简单的部分,它通过JSON数据执行
forEach
循环,定义
userCity
变量(让我更容易),然后记录日志以控制结果(这确实是不必要的,但我这样做是为了确认我正确地循环了JSON)

功能测试(){
const webexSiteUserListJson=fs.readFileSync('./src/db/webexSiteUserDetail.json');
const webexSiteUsers=JSON.parse(webexSiteUserListJson);
webexSiteUsers.forEach((userDetails)=>{
让userCity=userDetails['use:address']['com:city'];
console.log(用户城市);
})
};
我一直在寻找关于这个话题的帮助,但可能没有正确地阐述我的问题。对于如何: 1.遍历
['use:address']['com:city'
,绘制并识别所有城市。 2.然后确定与每个城市匹配的记录数(在上面的示例中,我将使用US-TX:1和US-CA:2)

谢谢!

您可以将
webexSiteUsers
数组放入一个由city设置关键帧的对象中,其中每个值都是city出现的次数。类似下面的方法应该可以工作

const counts = webexSiteUsers.reduce((countMemo, userDetails) => {
  let userCity = userDetails['use:address']['com:city'];
  if (countMemo[userCity]) {
    countMemo[userCity] = countMemo[userCity] + 1;
  } else {
    countMemo[userCity] = 1;
  }
  return countMemo;
}, {});
计数
将是一个如下所示的对象

{
  "US-TX": 1,
  "US-CA": 2
}

谢谢你,本杰明!如果不是你,我根本不知道减少多少。我已经在谷歌搜索了将近一个月,寻找答案。再次谢谢你。你让事情看起来很简单。