我有一个由三个不同对象组成的非规范化数组 - 国家、学校、学生
const input=
[
{
countryID: 12,
country: "US",
schoolID: 122,
schoolZone: "Highlands",
studentID: 142,
studentName: "Mary"
},
{
countryID: 12,
country: "US",
schoolID: 122,
schoolZone: "Highlands",
studentID: 145,
studentName: "John"
},
{
countryID: 14,
country: "UK",
schoolID: 222,
schoolZone: "Leeds",
studentID: 223,
studentName: "Peter"
}
];
我想像这样标准化它们
const result=
[
{
countryID: 12,
country: "US",
schools: [
{
schoolID: 122,
schoolZone: "Highlands",
students: [
{
studentID: 142,
studentName: "Mary"
},
{
studentID: 145,
studentName: "John"
}
]
}
]
},
{
countryID: 14,
country: "UK",
schools: [
{
schoolID: 222,
schoolZone: "Leeds",
students: [
{
studentID: 223,
studentName: "Peter"
}
]
}
]
}
];
我了解 lodash
和 ramda
可用于实现嵌套规范化
但是我对这两个库都是新手。
您能帮我实现吗?还想知道考虑到存在 schools
和 students
最佳答案
不使用 lodash 或 ramda 的方法可能是这样的。希望这会有所帮助。
const input= [{
countryID: 12,
country: "US",
schoolID: 122,
schoolZone: "Highlands",
studentID: 142,
studentName: "Mary"
}, {
countryID: 12,
country: "US",
schoolID: 122,
schoolZone: "Highlands",
studentID: 145,
studentName: "John"
}, {
countryID: 14,
country: "UK",
schoolID: 222,
schoolZone: "Leeds",
studentID: 223,
studentName: "Peter"
}];
const normalize = (data) =>
data.reduce((acc, { studentID, studentName, schoolID, schoolZone, countryID, country }) => {
const studentToAdd = { studentID, studentName };
const schoolToAdd = { schoolID, schoolZone, students: [studentToAdd] };
const countryToAdd = { countryID, country, schools: [schoolToAdd] };
const existingCountry = acc.find(item => item.countryID === countryID);
if (existingCountry) {
const existingSchool = existingCountry.schools.find(item => item.schoolID === schoolID);
if (existingSchool) {
const existingStudent = existingSchool.students.find(item => item.studentID === studentID);
if (!existingStudent) existingSchool.students.push(studentToAdd);
}
else existingCountry.schools.push(schoolToAdd);
}
else acc.push(countryToAdd);
return acc;
}, []);
console.log(normalize(input));
关于javascript - 使用 lodash.groupBy() 标准化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53457733/