Tengo un conjunto de resultados de DB como a continuación:
"result": [ { "customerId": "20572696", "totalIncome": "260000", "total_Expense": "130000", "relationName": "VIJAYA", "relationDOB": "23839", "relation": "Daughter" }, { "customerId": "20572696", "totalIncome": "260000", "total_Expense": "130000", "relationName": "Riyaz", "relationDOB": "26665", "relation": "SPOUSE" }, { "customerId": "20570000", "totalIncome": "200000", "total_Expense": "100000", "relationName": "John", "relationDOB": "26000", "relation": "SON" } ] Necesito formatear el conjunto de resultados como se muestra a continuación agrupando el ID del customerId , totalIncome total, el total_Expense y colocando el resto de los objetos en una matriz llamada relation .
"result": [{ "customerId": "20572696", "totalIncome": "260000", "total_Expense": "130000", "relations": [ { "relationName": "VIJAYA" "relationDOB": "23839 ", "relation": "Daughter " }, { "relationName": "Riyaz", "relationDOB": "26665", "relation": "SPOUSE" } ] }, { "customerId": "20570000", "totalIncome": "200000", "total_Expense": "100000", "relations": [ { "relationName": "John" "relationDOB": "26000", "relation": "SON" }] } ]Una forma en la que pienso es filtrar todos los ID de cliente distintos en una matriz separada y recorrer la matriz de resultados y separar los primeros tres campos y colocar los campos restantes en un objeto y empujarlo en una submatriz. Pero, ¿hay alguna manera elegante de hacer esto?
puedes hacer algo como esto con reduce y Object.values
básicamente con reduce creas un objeto con customerId como clave
luego, con Object.values, se deshace de los índices de identificación del cliente y obtuvo su resultado como una matriz
tenga en cuenta que, dado que 20570000 menor que 20572696 , cuando devuelve la matriz, el orden se invierte
const group = data => Object.values(data.reduce((res, {customerId, totalIncome, total_Expense, ...rest}) => { const existing = res[customerId] || {customerId, totalIncome, total_Expense, relations:[]} return { ...res, [customerId]: { ...existing, relations: [...existing.relations, rest] } } }, {})) const data = [ { "customerId": "20572696", "totalIncome": "260000", "total_Expense": "130000", "relationName": "VIJAYA", "relationDOB": "23839", "relation": "Daughter" }, { "customerId": "20572696", "totalIncome": "260000", "total_Expense": "130000", "relationName": "Riyaz", "relationDOB": "26665", "relation": "SPOUSE" }, { "customerId": "20570000", "totalIncome": "200000", "total_Expense": "100000", "relationName": "John", "relationDOB": "26000", "relation": "SON" } ] console.log(group(data))Si customerId , totalIncome y total_Expense son todos iguales, entonces:
const obj = {"result":[{"customerId":"20572696","totalIncome":"260000","total_Expense":"130000","relationName":"VIJAYA","relationDOB":"23839","relation":"Daughter"},{"customerId":"20572696","totalIncome":"260000","total_Expense":"130000","relationName":"Riyaz","relationDOB":"26665","relation":"SPOUSE"},{"customerId":"20570000","totalIncome":"200000","total_Expense":"100000","relationName":"John","relationDOB":"26000","relation":"SON"}]}; let relations = {}; let identifierFields = {}; obj.result.forEach(({ customerId, totalIncome, total_Expense, ...rest }) => { relations[customerId] = (relations[customerId] || []); relations[customerId].push({ ...rest }); if (!identifierFields[customerId]) identifierFields[customerId] = { customerId, totalIncome, total_Expense }; }); const result = Object.values(identifierFields).map((r, idx) => ({ ...r, relations: relations[r.customerId] })); console.log(result); .as-console-wrapper { max-height: 100% !important; top: auto; } Esto es más eficaz que simplemente difundir todo, ya que solo propaga las otras propiedades en el objeto y push todo lo demás, ahorrándole mucha memoria y pérdidas de tiempo.
Use forEach y cree un objeto con clave como ID de cliente y valor agregado para la misma ID.
const process = (data, track = {}) => { data.forEach(({ customerId, totalIncome, total_Expense, ...item }) => { if (!track[customerId]) { track[customerId] = { customerId, totalIncome, total_Expense, relations: [item], }; } else { track[customerId].relations.push(item); } }); return Object.values(track); }; const data =[{"customerId":"20572696","totalIncome":"260000","total_Expense":"130000","relationName":"VIJAYA","relationDOB":"23839","relation":"Daughter"},{"customerId":"20572696","totalIncome":"260000","total_Expense":"130000","relationName":"Riyaz","relationDOB":"26665","relation":"SPOUSE"},{"customerId":"20570000","totalIncome":"200000","total_Expense":"100000","relationName":"John","relationDOB":"26000","relation":"SON"}]; console.log(process(data)); .as-console-wrapper { max-height: 100% !important; top: auto; }