[英]groupBy or partitioning object with multiple keys with lodash
I have an array of packets so that each packet has source IP and destination IP.我有一个数据包数组,因此每个数据包都有源 IP 和目标 IP。 I want to find the best way to divide the array so that in the end I'll get a dictionary whose keys are IP and their value is all the packets sent from or to that IP.我想找到划分数组的最佳方法,这样最终我会得到一个字典,它的键是 IP,它们的值是从该 IP 发送或发送到该 IP 的所有数据包。
For example, if this is my array:例如,如果这是我的数组:
let packets = [ {sourceIp:127.0.0.1, destIp:127.0.0.2},
{sourceIp:127.0.0.2, destIp:127.0.0.3},
{sourceIp:127.0.0.3, destIp:127.0.0.1},
{sourceIp:127.0.0.2, destIp:127.0.0.1}]
I'm looking for a way to get-我正在寻找一种方法来获得-
result = { 127.0.0.1: [{sourceIp:127.0.0.1, destIp:127.0.0.2},{sourceIp:127.0.0.3, destIp:127.0.0.1},
{sourceIp:127.0.0.2, destIp:127.0.0.1}],
127.0.0.2: [{sourceIp:127.0.0.1, destIp:127.0.0.2},{sourceIp:127.0.0.2, destIp:127.0.0.3},
{sourceIp:127.0.0.2, destIp:127.0.0.1}],
127.0.0.3: [{sourceIp:127.0.0.2, destIp:127.0.0.3},{sourceIp:127.0.0.3, destIp:127.0.0.1}]
}
Thank you:-)谢谢:-)
First of all json array objects data type should be in string.首先,json 数组对象的数据类型应该是字符串。
Then use lodash in _.groupBy()然后在_.groupBy() 中使用lodash
const packets = [{ sourceIp: "127.0 .0 .1", destIp: "127.0 .0 .2" }, { sourceIp: "127.0 .0 .2", destIp: "127.0 .0 .3" }, { sourceIp: "127.0 .0 .3", destIp: "127.0 .0 .1" }, { sourceIp: "127.0 .0 .2", destIp: "127.0 .0 .1" } ] const splittedData = _.groupBy(packets, 'sourceIp'); console.clear(); console.log(splittedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Presuming sourceIp
& destinationIp
are always different (which seems reasonable), I would first duplicate the array so that you have 1 with source as "key", and 1 with destination as "key":假设sourceIp
和destinationIp
总是不同的(这似乎是合理的),我会首先复制数组,这样你就有 1 个源为“键”,1 个目标为“键”:
const packetsBySource = packets.map(({ sourceIp, destIp }) => ({ key: sourceIp, sourceIp, destIp }))
const packetsByDest = packets.map(({ sourceIp, destIp }) => ({ key: destIp, sourceIp, destIp }))
Then I would merge these together, and do a groupBy:然后我将这些合并在一起,并做一个 groupBy:
import groupBy from 'lodash/groupBy'
const both = [...packetsBySource, ...packetsByDest]
const keyed = groupBy(both, 'key')
key
property;您的对象仍将具有额外的key
属性; if this is a problem you will need: const keyedClean = mapValues(keyed, (packets) => packets.map(({ sourceIp, destIp }) => ({ sourceIp, destIp })))
如果这是一个问题,您将需要: const keyedClean = mapValues(keyed, (packets) => packets.map(({ sourceIp, destIp }) => ({ sourceIp, destIp })))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.