ধরি আমাদের নিচের মতো অবজেক্টের অ্যারে আছে:
const arr = [
{ "customer": "Customer 1", "project": "1" },
{ "customer": "Customer 2", "project": "2" },
{ "customer": "Customer 2", "project": "3" }
]
একই কাস্টমারের প্রজেক্টগুলো মার্জ করে নিচের মতো আউটপুট বানাতে হবে:
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' ] } ]