I have an array containing objects. Now I want to slice the array to a new object containing only those objects matching a certain property name and grouped by this property name. The thing is that I also have properties names that are different between them. The names and ID's repeat through the array of objects, but inside the new object, it should contain the ID and the name only once.
The original array looks like this:
let personArray = [
{
id_dentist: 1,
dentist_name: 'John',
id_secretary: 6,
secretary_name: 'Paul',
id_security: 3,
security_name: 'Carl'
},
{
id_dentist: 2,
dentist_name: 'Lisa',
id_secretary: 9,
secretary_name: 'Beth',
id_security: 5,
security_name: 'Monica'
},
{
id_dentist: 1,
dentist_name: 'John',
id_secretary: 6,
secretary_name: 'Paul',
id_security: 3,
security_name: 'Carl'
}
];
The new object should look like this:
let personObject = {
dentist: [
{ id_dentist: 1, dentist_name: 'John' },
{ id_dentist: 2, dentist_name: 'Lisa' },
],
secretary: [
{ id_secretary: 6, secretary_name: 'Paul' },
{ id_secretary: 9, secreatary_name: 'Beth' },
],
security: [
{ id_security: 3, security_name: 'Carl' },
{ id_security: 5, security_name: 'Monica' }
]
};
I appreciate the help.
As requested, I tried using reduce() and filter(), but I was not able to make them to split.
Here is the code:
const obj = personArray.reduce((acc, cur) => {
const key = Object.keys(cur).filter(f => /^id_/.test(f))[0].split('_')[1];
if (!acc[key]) acc[key] = [];
acc[key].push(cur);
return acc;
}, {});
console.log(obj);
About the strange data structure, I am getting those data from a database with a SELECT SQL syntax.