gpt4 book ai didi

node.js - NodeJS 迭代 JSON 中的 City,返回城市和每个城市的用户

转载 作者:太空宇宙 更新时间:2023-11-04 00:00:10 25 4
gpt4 key购买 nike

我有来自 JSON 对象的以下代码片段,其中包含 3,500 条记录。

[
{
"use:firstName": "Bob",
"use:lastName": "Smith",
"use:categoryId": 36,
"use:company": "BobSmith",
"use:webExId": "Bob.Smith@email.com",
"use:address": {
"com:addressType": "PERSONAL",
"com:city": "US-TX",
"com:country": 1
}
},
{
"use:firstName": "Jane",
"use:lastName": "Doe",
"use:categoryId": 36,
"use:webExId": "Jane.Doe@email.com",
"use:address": {
"com:addressType": "PERSONAL",
"com:city": "US-CA",
"com:country": "1_1"
}
}
{
"use:firstName": "Sam",
"use:lastName": "Sneed",
"use:categoryId": 36,
"use:webExId": "Sam.Sneed@email.com",
"use:address": {
"com:addressType": "PERSONAL",
"com:city": "US-CA",
"com:country": "1_1"
}
}
]

我正在使用 NodeJS,并且我一直在寻找最好的方法: 1. 迭代['use:address']['com:city'以绘制并识别所有城市。 (在上面的示例中,我提供的三个记录中有两个:US-TXUS-CA) 2. 然后确定有多少条记录与每个城市匹配(在上面的示例中,我有 US-TX: 1 和 US-CA: 2)

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

function test() {
const webexSiteUserListJson = fs.readFileSync('./src/db/webexSiteUserDetail.json');
const webexSiteUsers = JSON.parse(webexSiteUserListJson);
webexSiteUsers.forEach((userDetails) => {
let userCity = userDetails['use:address']['com:city'];
console.log(userCity);
})
};

我一直在无休止地寻求有关该主题的帮助,但可能没有正确地表达我的问题。任何关于如何: 1. 迭代['use:address']['com:city'以绘制并识别所有城市。 2. 然后确定有多少条记录与每个城市匹配(在上面的示例中,我有 US-TX: 1 和 US-CA: 2)

谢谢!

最佳答案

你可以reducewebexSiteUsers 数组转换为以城市为键的对象,其中每个值都是该城市出现的次数。像下面这样的东西应该可以工作。

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;
}, {});

counts 将是一个如下所示的对象。

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

关于node.js - NodeJS 迭代 JSON 中的 City,返回城市和每个城市的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55151705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com