Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

297
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda