Hello friends I have the following json and I need to transform it to the following but we really don't know how to do it.
[
{ organizacion: 'empresa1', usuario: 'andres', rol: 'admin' },
{ organizacion: 'empresa1', usuario: 'andres', rol: 'superadmin' },
{ organizacion: 'empresa1', usuario: 'carlos', rol: 'write' },
{ organizacion: 'empresa2', usuario: 'andres', rol: 'admin' },
{ organizacion: 'empresa2', usuario: 'juan', rol: 'write' },
{ organizacion: 'empresa2', usuario: 'juan', rol: 'editor' }
]
I have to pass this
[
{ empresas: “empresa1”,
usuarios: [{
username: “andres”,
roles: [“admin”,”superadmin”] }
{
username: “carlos”,
roles: [“writer”] }
]
},
{
empresas:”empresa2”,
…
}]
There really comes a point where I start to get confused, and that is that I don't know how to enter and validate. This is what I did-
let organizaciones = [];
let usuarios = [];
info.forEach(element => {
organizaciones.push(element.organizacion);
usuarios.push(element.usuario);
});
organizaciones = organizaciones.filter((item, index) => {
return organizaciones.indexOf(item) === index;
})
usuarios = usuarios.filter((item, index) => {
return usuarios.indexOf(item) === index;
})
for (let i = 0; i < organizaciones.length; i++) {
resumen.push({
organizacion: info[i].organizacion,
users: [{
username: info[i].usuario,
roles: [info[i].rol]
}]
});
}
Very good, I think I have solved your problem, I will try to explain how I have done it, it may be possible to make it less extensive but it does not give me the mind for more.
First your initial JSON, which I have called
tabla
Subsequently your output JSON, which I have called
objetos
It is an array that will contain the new objects created from the
tabla
or your previous JSON.First
if
, check theorganizacion
In this if we check that your output JSON, which I have called,
objetos
meets one of two conditions, these conditions are:organizacion
the position is different from theorganizacion
initial JSON that I calledtabla
If any of these are met, we are facing the simplest thing, which is to have found a user and a company that we can directly insert all the content of the previous JSON (
tabla
)Second
if
, checkusuario
In this second, the users are checked and both the user and the role are entered if the following condition is met:
objetos
is different from thetabla
means that the condition of being able to introduce a new user that is not repeated is met, so there is no need to check the roles, otherwise (the else of this if) means that there is already a user and we only keep the role, to introduce it in the roles array.dfg
All together it should be something like the following
I apologize if I have convoluted it too much, there may be a less convoluted way but I have not found it, I hope it will help you even if they remain to be verified, such as the fact that the roles are not repeated, but since I do not know what you need I will leave it now in your hands.