Last active
August 19, 2022 14:21
-
-
Save ingeit/1871fd6acd34019e3b67eb4dd25065b4 to your computer and use it in GitHub Desktop.
agrupar propiedas en js, datos repetidos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// parametros: array de la respuesta a agrupar | |
// groupBy: propiedad por la que se quiere agrupar EJ: id repetidos | |
// newProp: nueva propiedad a generar con la informacion que me genera lineas repetidas | |
// props: array de propiedades a generar en la newProp y finalmente borrarlas | |
//===================================================================================== | |
// EJEMPLO DE USO | |
// listar() { | |
// return this.http.get<any>(`${urlServidor}/`).toPromise() | |
// .then(res => { | |
// return this.agruparSegun(res.respuesta, 'idEvento', 'precios', ['importe', 'tipo', 'idPrecio', 'precioEstado']) | |
// }) | |
// } | |
//===================================================================================== | |
const agruparSegun = (array, groupBy, newProp, props) => { | |
const objeto = array.reduce((groups, item) => ({ | |
...groups, | |
[item[groupBy]]: groups[item[groupBy]] | |
? { ...item, [newProp]: [...groups[item[groupBy]][newProp], crearObjectoAuxiliar(props, item)] } | |
: { ...item, [newProp]: [crearObjectoAuxiliar(props, item)] } | |
}), {}); | |
deleteProps(objeto, props) | |
return Object.keys(objeto).map(x => objeto[x]); | |
} | |
const crearObjectoAuxiliar = (props, item) => { | |
let aux = {}; | |
props.forEach(element => { | |
aux[element] = item[element] | |
}); | |
return aux; | |
} | |
const deleteProps = (objeto, props) => { | |
props.forEach(element => { | |
for (let o in objeto) { | |
delete objeto[o][element] | |
} | |
}); | |
} | |
export { agruparSegun }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment