我正在尝试将来自MySql right join
的行数组转换为nodeJS上的array/json
格式。考虑通用的mysql表:
emp_id name
1 john
2 bill
3 anna
fk_emp_id project
1 p1
1 p2
1 p3
2 p1
2 p4
他们正确加入:
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
这是:
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}
]
如何将它们转换为此JSON:
result = [
{id: '1',
name: 'john',
projects: [p1, p2, p3]
}
,
{id: '2',
name: 'bill',
projects: [p1, p4]
}
,
{id: '3',
name: 'anna',
projects: []
}
]
答案 0 :(得分:1)
如果您只查看将result
转换为id
数组的版本,则可以使用Map
作为哈希表,以获取给定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; }
class Post < ActiveRecord::Base
has_many :taggings
has_many :tags, through: :taggings
has_many :collectables
has_many :collections, through: :collectables
end