I have an array of objects in the below form it has three properties serviceName, pool, and environment I want to group the object based on environment and at the same time need to concat the pools:
const data = [
{
serviceName: "visa",
pool: "3g",
environment: "test-int",
},
{
serviceName: "visa",
pool: "4g",
environment: "test-int",
},
{
serviceName: "visa",
pool: "5g",
environment: "test-int",
},
{
serviceName: "amex",
pool: "5g",
environment: "dev",
},
{
serviceName: "amex",
pool: "6g",
environment: "dev",
},
];
I want the output in the below format:
const output = [
{
serviceName: "visa",
pool: "3g,4g,5g",
environment: "test-int"
},
{
serviceName: "amex",
pool: "5g,6g",
environment: "dev"
},
]
Based on my current code it just returns a single object instead of an array of objects:
const output = data.reduce((acc, ar) => {
let res = {
...acc,
pool: acc["pool"] + "," + ar.pool
};
return res;
}
});
poolis probably more useful as an array instead of a string. Alsoreduce()returns a single result as you've already experienced.