Azevedo Azevedo - 2 months ago 16
Javascript Question

SQL right join to JSON/array

I'm trying to convert an array of rows coming from a MySql

right join
into an
array/json
format on nodeJS. Considering the generic mysql tables:

emp_id name
1 john
2 bill
3 anna


fk_emp_id project
1 p1
1 p2
1 p3
2 p1
2 p4


And a right join of them:

id name fk_emp_id project
1 john 1 p1
1 john 1 p2
1 john 1 p3
2 bill 2 p1
2 bill 2 p4
3 anna 3 null


Which is:

rows = [
{"id":1, "name":"john", "fk_emp_id" : "1" , "project" : "p1"},
{"id":1, "name":"john", "fk_emp_id" : "1" , "project" : "p2"},
{"id":1, "name":"john", "fk_emp_id" : "1" , "project" : "p3"},
{"id":2, "name":"bill", "fk_emp_id" : "2" , "project" : "p1"},
{"id":2, "name":"bill", "fk_emp_id" : "2" , "project" : "p4"},
{"id":3, "name":"anna", "fk_emp_id" : "3" , "project" : null}
]


How do I convert them to this JSON:

result = [
{id: '1',
name: 'john',
projects: [p1, p2, p3]
}
,
{id: '2',
name: 'bill',
projects: [p1, p4]
}
,
{id: '3',
name: 'anna',
projects: []
}
]

Answer

If you look only for a version to convert your rows to result array, then you could use a Map as hash table for the reference of the given id.

var rows = [{ id: 1, name: "john", fk_emp_id: "1", project: "p1" }, { id: 1, name: "john", fk_emp_id: "1", project: "p2" }, { id: 1, name: "john", fk_emp_id: "1", project: "p3" }, { id: 2, name: "bill", fk_emp_id: "2", project: "p1" }, { id: 2, name: "bill", fk_emp_id: "2", project: "p4" }, { id: 3, name: "anna", fk_emp_id: "3", project: null }],
    result = [];

rows.forEach(function (a) {
    var reference = this.get(a.id);
    if (!reference) {
        reference = { id: a.id, name: a.name, fk_emp_id: a.fk_emp_id, projects: [] };
        this.set(a.id, reference);
        result.push(reference);
    }
    a.project && reference.projects.push(a.project);
}, new Map);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }