The description is confusing alongside the code.
I'm trying to match the mac address with IP. and if they matched put them beside the circle.
Do you mean match a section of the MAC address to a section of the IP address ?
A MAC address in your example looks like this: 00:11:1f:10:11:13
.
An IP address in your example looks like this: 10.11.2.1
.
Do you mean compare the parts that aren't the same across rows (e.g. 00:11:1f:10:11:13 to 10.11.2.1 )?
Your conditions suggests otherwise:
if (table.getRow(i).arr[1] = '00:11:1F:AC:ba:39')
It attempts to match any row with MAC address 00:11:1F:AC:ba:39
.
Notice that arr[1]
points to the second CSV column: "Model".
The MAC address is the forth column (at index 3 (e.g. table.getRow(i).arr[3]
))
Alternatively you can retrieve it by colum name since the CSV has a header:
table.getRow(i).obj["MAC address"]
If you're looping through all the rows a single for loop should do.
Additionally you need to handle the edge case of the MAC address not being in the list.
e.g.
let foundIP = null;
for (let i = 0; i < table.getRowCount(); i++){
let currentRow = table.getRow(i);
if (currentRow.obj['MAC address'] === '00:11:1F:AC:ba:39'){
foundIP = currentRow.obj['IP address'];
break;
}
}
if(foundIP){
console.log('foundIP',foundIP);
}else{
console.log('no IP found for MAC 00:11:1F:AC:ba:39');
}
Notice that:
- currentRow is re-used (as opposed to calling
table.get()
multiple times per loop): this pays off especially when you have to process many rows
- in JS
==
works, but ===
is recommended since it also checks if the data type matches
break
is used to break out of the for loop once a match has been found. (if it hasn't foundRow will not have a valid value)
This can easily be encapsulated in a re-usable function:
function findIP(table, macAddress) {
for (let i = 0; i < table.getRowCount(); i++) {
let currentRow = table.getRow(i);
if (currentRow.obj['MAC address'] === macAddress) {
return currentRow.obj['IP address'];
}
}
}
In this case, the result is either the IP (if found) or undefined
(if no matches were found):
let macToFind = '00:11:1F:AC:ba:39'
let foundIP = findIP(table, macToFind);
if (foundIP) {
console.log('foundIP', foundIP);
} else {
console.log('no IP found for MAC ' + macToFind);
}
This should make it flexible enough to search multiple tables and mac addresses if needed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…