Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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' ] }
]Advertisements