2

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: []
    }
]
1
  • You can use Json-lib from below url to convert it to formatted the JSON. json-lib.sourceforge.net Commented Sep 19, 2016 at 16:20

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.