The title explains it pretty well, but I’m trying to build a ‘for loop’ that matches a variable (in this case, one garnered by an HTML5 form) to a value in a cell in a 2-column database. Then I want to ‘console.log’ the value in the adjacent (next column over) cell.
Looking for coding help and any suggestions for what type of database would work best with this type of arrangement.
var myDB = {AA:100, BB:50, CC:75, DD:66, EE:40};
function DB(value) {
return myDB[value];
}
console.log(DB('AA'));
It seems to be the best approach for this would be to have a data structure like this:
This would remove the need for a “for loop” as you were planning to use which is incredibly inefficient and would enable you to use a simple index check like this:
If you need to be able to search on either index, then you’ll need to make a slightly more complex database layout (I’m assuming your “database” is actually just javascript data since you wanted to console.log the data.
If you’re looking to do this in a server side database and return the data, you’ll need AJAX functionality and server side APIs to post those ajax requests to and return your data in JSON. Which is slightly more complicated than what I just suggested above.
Update:
If you wanted to “search” the database values and find the matching key, you would probably have to either run a for loop on the myDB object, or build your database a little differently by having a separate object for each of the keys and one for the data. Something like this:
Now you can “search” on either of the index columns and get the ID of the data row that corresponds to that matched column. This data structure is very similar to how indexes are used in most databases like MySQL and others. So your “search” function would likely look something like this: