I have the below user data.The data was nested on 2 levels and flattening it doesn’t work
[
[
{ class_id: "Grade 1", roll_number: "1", name: "alex" },
{ class_id: "Grade 1", roll_number: "2", name: "bob" },
],
[
{ class_id: "Grade 2", roll_number: "7", name: "peter" },
{ class_id: "Grade 3", roll_number: "6", name: "lia" },
{ class_id: "Grade 2", roll_number: "5", name: "mary" },
{ class_id: "Grade 3", roll_number: "1", name: "violet" },
],
]
Requirement is that I have to generate data taking into account of the class_id and generate information as below
[
{
class_id: "Grade",
students: [
{ roll_number: "1", name: "alex" },
{ roll_number: "2", name: "boc" },
],
},
{
class_id: "Grade 2",
students: [
{ roll_number: "7", name: "peter" },
{ roll_number: "5", name: "mary" },
],
},
{
class_id: "Grade 3",
students: [
{ roll_number: "6", name: "lia" },
{ roll_number: "1", name: "violet" },
],
},
]
I have tried using the below piece of code
var response = [];
data.map(item => {
var students = [];
for (var i = 0; i < item.length; i++) {
const stu_obj = {
name: item[i].name,
roll_number: item[i].roll_number,
};
students.push(stu_obj);
if (i == 0) {
const class_obj = {
class_id: item[0].class_id,
studentsList: students,
};
response.push(class_obj);
continue;
}
}
});
But it doesn’t work for cases where the item in array has multiple class_ids. What should I do?
3
Answers
If you use the
flat
method on the data array you can iterate over the objects in the flattened array to process them.If you’re trying to assign things to an object with a specific id one of the simpler methods is to create an object with that id as its key name, and then assign the object you want to contain the relevant data as its value. Then, at the end of the iteration, you can grab the
Object.values
as an array of objects matching your criteria.Here’s an example using
reduce
.You can flatten the array, then iterate over it while using an object to store an array for each
class_id
.So you want to group your
students
byclass_id
and then organize that data as an array.I’m not sure what the original structure is, can it only be nested 1 level deep? If so, then code like this should work: