मान लीजिए हमारे पास इस तरह का ऑब्जेक्ट्स का ऐरे है:
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' ] }
]