Matthew Moon Matthew Moon - 5 months ago 8
Javascript Question

How to get properties of one array of objects into another array of objects

Here's what I've got. One array of objects:

var teachers = [{
Year: 2016,
FullName: "Matt",
Age: 39
},
{
Year: 2016,
FullName: "Sara",
Age: 25
},
...
];


And another array of objects. These would be nested like so:

var students = [[
{
Year: 2016,
FullName: "Zoe"
Age: 8
}
],
[
{
Year: 2016,
FullName: "Lulu"
Age: 9
},
{
Year: 2016,
FullName: "Leo",
Age: 13
}
],
[ // empty array here
],
[
{
Year: 2016,
FullName: "Lotta",
Age: 11
}
]
...
];


How they are organized is that students[0] is a student of teachers[0]. students[4] are students of teachers[4], and so forth.

What I was attempting to do what to take the FullName property, 'Students' in each student and put those values into an array of a new property of teachers called 'SundayStudents'. So what I'd end up with would be:

teachers = [{
Year: 2016,
FullName: "Matt",
Age: 39,
SundayStudents: ["Zoe"]
},
{
Year: 2016,
FullName: "Sara",
Age: 25,
SundayStudents: ["Lulu", "Leo"]
},
...
];


I tried a nested for-loop, but the students array has varying numbers of objects in each sub-array, and it doesn't create an array for the new property. I think I'm stuck.

for (var j = 0, leng = teachers.length; j < leng; j++) {
for (var k = 0, lent = students.length; k < lent; k++)
Teachers[i].SundayStudents = Students[j][k].FullName;
}


Any hints are welcome.

Answer

You could just iterate and check if the target element exist. Then you could make a new property with the mapped names.

var teachers = [{ Year: 2016, FullName: "Matt", Age: 39 }, { Year: 2016, FullName: "Sara", Age: 25 }],
    students = [[{ Year: 2016, FullName: "Zoe", Age: 8 }], [{ Year: 2016, FullName: "Lulu", Age: 9 }, { Year: 2016, FullName: "Leo", Age: 13 }], [{ Year: 2016, FullName: "Lotta", Age: 11 }]];

students.forEach(function (a, i) {
    if (Array.isArray(a) && teachers[i]) {
        teachers[i].SundayStudents = a.map(function (b) {
            return b.FullName;
        });
    }
});

console.log(teachers);