forked from avivarachel/node-mysql-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise-3.js
40 lines (38 loc) · 1.1 KB
/
exercise-3.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
var mysql = require('mysql');
var colors = require('colors/safe');
var connection = mysql.createConnection({
host : process.env.IP,
user : process.env.C9_USER,
password : '',
database : 'addressbook'
});
connection.query("SELECT Account.id, AddressBook.accountId, Account.email, AddressBook.name FROM Account JOIN AddressBook on Account.id=AddressBook.accountId",
function(err, rows){
// rows.forEach(function(row) {
// console.log(colors.bold('#' + row.id + ': ' + row.email + row.name));
// });
var accounts = rows.reduce(
function(acc,curr){
var idx = acc.findIndex(function (item) {
return item.accountId === curr.accountId;
});
if (idx >-1) {
acc[idx].accounts.push({
name: curr.name
});
} else {
acc.push({
accountId: curr.accountId,
email: curr.email,
accounts: [{
name: curr.name
}]
})
}
return acc;
}, []
);
//console.log(accounts);
console.log(JSON.stringify(accounts,null,2));
connection.end();
})