我正在尝试结合JSON对象的值以显示发往特定目标的流量的完整吞吐量,而不是显示相同地址的微小值。
我已经阅读了数百个线程,它们似乎都围绕着使用单个键将不同数组中的值添加到一个数组中,或者将这些值组合到一个字段中来进行。
此处的关键是IP地址,要添加的值是RX和TX
我的数据如下所示:
[
{"macProtocol": "ip", "ipProtocol": "tcp", "dstAddress": "X.60.219.13", "tx":50, "rx":100},
{"macProtocol": "ip", "ipProtocol": "tcp", "dstAddress": "X.60.219.13", "tx":50, "rx":100},
{"macProtocol": "ip", "ipProtocol": "tcp", "dstAddress": "X.60.219.13", "tx":50, "rx":100},
{"macProtocol": "ip", "ipProtocol": "tcp", "dstAddress": "X.60.219.13", "tx":50, "rx":100},
{"macProtocol": "ip", "ipProtocol": "udp", "dstAddress": "X.172.63.97", "tx":500, "rx":750},
{"macProtocol": "ip", "ipProtocol": "udp", "dstAddress": "X.189.157.90", "tx":1000, "rx":2776},
{"macProtocol": "ip", "ipProtocol": "udp", "dstAddress": "X.212.176.21", "tx":70, "rx":300},
]
我想将其转换为:
[
{"macProtocol": "ip", "ipProtocol": "tcp", "dstAddress": "X.60.219.13", "tx": 200, "rx": 400},
{"macProtocol": "ip", "ipProtocol": "udp", "dstAddress": "X.172.63.97", "tx": 500, "rx": 750},
{"macProtocol": "ip", "ipProtocol": "udp", "dstAddress": "X.189.157.90", "tx": 1000, "rx": 2776},
{"macProtocol": "ip", "ipProtocol": "udp", "dstAddress": "X.212.176.21", "tx": 70, "rx": 300},
]
您可以创建目标地址的哈希:
let data = [
{
macProtocol: 'ip',
ipProtocol: 'tcp',
dstAddress: 'X.60.219.13',
tx: 50,
rx: 100,
},
{
macProtocol: 'ip',
ipProtocol: 'tcp',
dstAddress: 'X.60.219.13',
tx: 50,
rx: 100,
},
{
macProtocol: 'ip',
ipProtocol: 'tcp',
dstAddress: 'X.60.219.13',
tx: 50,
rx: 100,
},
{
macProtocol: 'ip',
ipProtocol: 'tcp',
dstAddress: 'X.60.219.13',
tx: 50,
rx: 100,
},
{
macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'X.172.63.97',
tx: 500,
rx: 750,
},
{
macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'X.189.157.90',
tx: 1000,
rx: 2776,
},
{
macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'X.212.176.21',
tx: 70,
rx: 300,
},
];
const reducedArr = Object.values(
/*obj: {
'X.212.176.21': {
macProtocol: 'ip',
ipProtocol: 'udp',
dstAddress: 'X.212.176.21',
tx: 70,
rx: 300,
},
'X...':{},
.....
}*/
data.reduce((obj, {dstAddress:dAdd,...curr}) => {
if (dAdd in obj) {
['tx', 'rx'].forEach(x => (obj[dAdd][x] += curr[x]));
} else {
obj[dAdd] = curr;
}
return obj;
}, {})
);
console.log(reducedArr);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句