How to iterate an array of objects and build a new one in JavaScript ?


Suppose, we have an array of objects like this −

const arr = [
   {
      "customer": "Customer 1",
      "project": "1"
   },
   {
      "customer": "Customer 2",
      "project": "2"
   },
   {
      "customer": "Customer 2",
      "project": "3"
   }
]

We are required to write a JavaScript function that takes one such array, and yields (returns) a new array.

In the new array, all the customer keys with same values should be merged and the output should look something like this −

const output = [
   {
      "Customer 1": {
         "projects": "1"
      }
   },
   {
   "Customer 2": {
      "projects": [
         "2",
         "3"
      ]
   }
}
]

Example

Let us write the code −

const arr = [
   {
      "customer": "Customer 1",
      "project": "1"
   },
   {
      "customer": "Customer 2",
      "project": "2"
   },
   {
      "customer": "Customer 2",
      "project": "3"
   }
]
const groupCustomer = data => {
   const res = [];
   data.forEach(el => {
      let customer = res.filter(custom => {
         return el.customer === custom.customer;
      })[0];
      if(customer){
         customer.projects.push(el.project);
      }else{
         res.push({ customer: el.customer, projects: [el.project] });
      };
   });
   return res;
};
console.log(groupCustomer(arr));

Output

And the output in the console will be −

[
   { customer: 'Customer 1', projects: [ '1' ] },
   { customer: 'Customer 2', projects: [ '2', '3' ] }
]

Updated on: 20-Nov-2020

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements