Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

298
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!