다음과 같은 객체 배열이 있다고 가정해 보겠습니다. -
const arr = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
] 우리는 그러한 배열을 취하고 새로운 배열을 산출(반환)하는 JavaScript 함수를 작성해야 합니다.
새 배열에서 동일한 값을 가진 모든 고객 키가 병합되어야 하며 출력은 다음과 같아야 합니다. -
const output = [
{
"Customer 1": {
"projects": "1"
}
},
{
"Customer 2": {
"projects": [
"2",
"3"
]
}
}
] 예시
코드를 작성해 보겠습니다 -
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)); 출력
콘솔의 출력은 -
[
{ customer: 'Customer 1', projects: [ '1' ] },
{ customer: 'Customer 2', projects: [ '2', '3' ] }
]