Created
November 20, 2020 20:45
-
-
Save flleeppyy/39278ef20a6055e75c366085dc25b7a1 to your computer and use it in GitHub Desktop.
sqlite3 multiple rows to a more formatted object.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// PLEASE NOTE THIS WORKS ONLY FOR TABLES WITH 2 COLUMNS | |
/** | |
* Lets say you have a database table that has some settings for a web application, | |
* that has two columns: option, and value, and you need to retrieve those settings. | |
* The way node-sqlite3 returns them is like the following | |
* QUERY: SELECT * FROM users WHERE option IN ('servername', 'serveradmincontact', 'loginenabled') | |
**/ | |
results = [ | |
{ option: 'servername', value: 'BlogApp' }, | |
{ option: 'serveradmincontact', value: '[email protected]' }, | |
{ option: 'loginenabled', value: '1' } | |
] | |
/** | |
* What the following code snippet does, is loop over each row, and take the | |
* first column and second column, and make that a new pair, then adds it to a new object. | |
* to put it in better words, it takes the option and value, and makes that a new pair | |
**/ | |
let formattedResults = {} | |
results.forEach(row => { | |
a = row.option; | |
b = row.value; | |
newvalues[a] = b | |
}); | |
// The formatted results now look like the following | |
formattedResults = { | |
'servername': 'BlogApp', | |
'serveradmincontact': '[email protected]`, | |
'loginenabled': '1' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment