I have an array with student and parent addresses.
For example,
const users = [{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'USA',
relationship:'mother'
},
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'Spain',
relationship:'father'
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
age: 28,
parent_address: 'France',
relationship:'father'
}
];
I'm trying to reformat this to the following result.
const list = [
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent: [
{
parent_address: 'USA',
relationship:'mother'
},{
parent_address: 'Spain',
relationship:'father'
}
]
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
age: 28,
parent:[
{
parent_address: 'France',
relationship:'father'
}
]
}
];
So far I tried the following way. I'm not sure that is the right way or not.
const duplicateInfo = [];
for (var i = 0; i < user[0].length; i++) {
var parent = [];
if (duplicateInfo.indexOf(user[0][i].id) != -1) {
// Do duplicate stuff
} else {
// Do other
}
duplicateInfo.push(user[0][i].id);
}
parent_addressandrelationshipin to aparentobject, and merge them when a duplicate name and email address are found.const list = []at first, but at the bottom you iterate over that list apparently by iterating overuser[0]. Your example code should be consistent.