JSFiddle - React, Tailwind, and code Playground
JavaScript
var data = [{
prod_name:"test1", type:"1", color:"white", product_id:"5"
},
{
prod_name:"test2", type:"1", color:"green", product_id:"7"
},
{
prod_name:"test2", type:"2", color:"green", product_id:"7"
},
{
prod_name:"test3", type:"4", color:"red", product_id:"8"
},
{
prod_name:"test4", type:"2", color:"white", product_id:"21"
}
];
[
{
prod_name:"test1", type:"1", color:"white", product_id:"5"
},
{
prod_name:"test2", type:"1,2", color:"green", product_id:"7"
},
{
prod_name:"test3", type:"4", color:"red", product_id:"8"
},
{
prod_name:"test4", type:"2", color:"white", product_id:"21"
}
];
var res = {};
$.each(data, function (key, value) {
if (!res[value.product_id]) {
res[value.product_id] = value;
} else {
res[value.product_id].type = [res[value.product_id].type, value.type].join(',');
}
});
data = $.map(res, function (value) {
return value;
});
console.log(data);