Merging Objects In Array Based On Sub-value
I have an array populated with objects. How do I go about merging objects inside this array when they have a matching specific sub value? My array looks like this: var data = [
Solution 1:
What I do in example bellow., first I create object to achieve unique values (by project_id
), and then converted object to array. In first loop I check if item does not exists in res
- put to res
, else I change only property type
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);
Post a Comment for "Merging Objects In Array Based On Sub-value"