gpt4 book ai didi

javascript - 如何从 JSON 中获取包含 javascript 中重复项的计数?

转载 作者:行者123 更新时间:2023-11-30 12:14:19 25 4
gpt4 key购买 nike

我有如下 JSON,

var json =
[
{"cardAid":"ALPHG","displayName":"ALPHG","SequenceNumber":"0","port":"A"},
{"cardAid":"ALPHG","displayName":"ALPHG","SequenceNumber":"1","port":"B"},
{"cardAid":"SFD","displayName":"SFD","SequenceNumber":"2","port":"C"},
{"cardAid":"SFD","displayName":"SFD","SequenceNumber":"3","port":"D"},
{"cardAid":"ALPHG","displayName":"ALPHG","SequenceNumber":"4","port":"E"},
{"cardAid":"ALPHG","displayName":"ALPHG","SequenceNumber":"5","port":"F"},
{"cardAid":"BETA","displayName":"BETA","SequenceNumber":"6","port":"G"}
];

我使用代码从这个链接解析这个 JSON, TO Get the number of Count from JSON in javascript?

function count(arr) {
var map = {};
for (var i = 0; i < arr.length; i++) {
var name = arr[i].cardAid;
var port = arr[i].port;
if (name in map){
map[name].Count++;
map[name].Port += ',' + port;
} else {
map[name] = { Count: 1, Port: port };
}
}
return map;
}

此函数使用 cardAid 作为键解析 JSON,并给出输出,

{
ALPHG: { Count: 4, Port: "A,B,E,F" },
SFD: { Count: 2, Port: "C,D" },
BETA: { Count: 1, Port: "G" }
}

但我需要基于 JSON 中的 SequenceNumber 的输出,

{
ALPHG: { Count: 2, Port: "A,B" },
SFD: { Count: 2, Port: "C,D" },
ALPHG: { Count: 2, Port: "E,F" },
BETA: { Count: 1, Port: "G" }
}

我如何根据 JSON 中的 SequenceNumber 将这个重复名称放入 Map 中

最佳答案

这可能接近您的想法 ( jsfiddle ),我选择将 Port 作为数组而不是字符串。但我有点困惑,因为 SequenceNumber 在此逻辑中没有影响,也许元素应该首先按 SequenceNumber 排序?

function count(data) {
var result = {};

for (var i = 0; i < data.length; ++i) {
var cardAid = data[i].cardAid;

if (!(cardAid in result)) {
result[cardAid] = [];
}

// Check if a new "sequence" needs to be created
if (i == 0 || data[i-1].cardAid != cardAid) {
result[cardAid].push({ Count: 0, Port: [] });
}

// Append item to the latest sequence
var lastIndex = result[cardAid].length - 1;
++result[cardAid][lastIndex].Count;
result[cardAid][lastIndex].Port.push(data[i].port);
}

return result;
}

结果:

{
"ALPHG": [
{
"Count": 2,
"Port": [ "A", "B" ]
},
{
"Count": 2,
"Port": [ "E", "F" ]
}
],
"SFD": [
{
"Count": 2,
"Port": [ "C", "D" ]
}
],
"BETA": [
{
"Count": 1,
"Port": [ "G" ]
}
]
}

关于javascript - 如何从 JSON 中获取包含 javascript 中重复项的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845989/

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