Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

290
Vistas
How can I destructing array and group them as objects in another array in JS?

I have a result set from DB like below:

"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"
    }
]

I need to format the result set like below by grouping the customerId, totalIncome, total_Expense and placing rest of the objects in array named 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"
            }]
    }
]

One way I think of is filtering all distinct customerId in a separate array and looping through result array and separate first three fields and placing remaining fields in a object and push it in a sub array. But is there any elegant way of doing this?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you can do something like this with reduce and Object.values

basically with reduce you create an object with customerId as key

then with Object.values you get rid of the customerId indices and you got your result as an array

be aware that since 20570000 in smaller than 20572696 when you return the array the order are inverted

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))

about 4 years ago · Juan Pablo Isaza Denunciar

0

If the customerId, totalIncome and total_Expense are all the same, then:

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; }

This is more performant than simply spreading everything, as it only spreads the other properties in the object and pushes everything else, saving you a lot of memory and time losses.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Use forEach and build an object with key as customerId and value as aggregated for same 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; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda