Home > database >  Setting Value from Dictionary To HTML Table - Javascript
Setting Value from Dictionary To HTML Table - Javascript

Time:12-16

I am new to Javascript Dictionary

I have few mac address in my router web terminal. I am trying to convert mac addresses to name so I had created a dictionary with all the translations. Now when I am logging the value it gives correct result but when I supply it to HTML table. Table sets undefined and also log undefined

The code is below...

const macAddressDictionary = {
    "74:C1:7D:C8:E4:D6": "Sunny", 
    "FA:16:11:D3:B7:84": "Kamran Sir",
    "44:5E:CD:B2:91:14": "Usman",
    "20:79:18:F0:DB:9C": "Usman-PC", 
    "66:EA:8E:E5:60:C3": "Arif",
    "F2:74:6E:25:91:B1": "Danish",
}
var table = document.getElementById("staTbl");
for (var i = 0, row; row = table.rows[i]; i  ) {  
for (var j = 0, col; col = row.cells[j]; j  ) {
    console.log(macAddressDictionary[row.cells[1].innerHTML]);  
    row.cells[1].innerHTML = macAddressDictionary[row.cells[1].innerHTML];
  }  
}

Output;

VM3694:13 undefined
VM3694:13 Sunny
5VM3694:13 undefined
VM3694:13 Kamran Sir
5VM3694:13 undefined
VM3694:13 Usman
5VM3694:13 undefined
VM3694:13 Usman-PC
5VM3694:13 undefined
VM3694:13 Arif
5VM3694:13 undefined
VM3694:13 Danish
5VM3694:13 undefined
undefined

Chrome Output

If I use "if logic" like below. It also sets the value in the table. But I dont know how to achieve this with dictionary

for (var j = 0, col; col = row.cells[j]; j  ) {
if (row.cells[1].innerHTML == "74:C1:7D:C8:E4:D6") {
 row.cells[1].innerHTML = "Sunny";
  }
}

enter image description here

CodePudding user response:

In essense what you are doing is looking at each column of the table and check if the content of that column exists in the dictionary, it is normal it is normal that you get 6 console logs (the amount of keys stored in the dictionary) and 40 undefined because the rest of the keys don't exist in the dictionary

the easiest thing you can do this is check if they key exists in the dictionary

const has = Object.prototype.hasOwnProperty
const table = document.getElementById("staTbl");
for (let i = 0, row; row = table.rows[i]; i  ) {  
    for (var j = 0, col; col = row.cells[j]; j  ) {
    
    // check if dictionary has the key
     if (has.call(macAddressDictionary,row.cells[1].innerHTML)) {
      row.cells[1].innerHTML = macAddressDictionary[row.cells[1].innerHTML]
     }
    }
}
  • Related