Combining objects in an array based on a sub-value
I have an array filled with objects. How do I concatenate objects within this array when they have a corresponding specific sub value?
My array looks like this:
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"
}
];
I want to combine objects based on matching product_id
.
If the values ββare not the same, I want to keep the BOTH values ββseparated by comma. Thus, the result of the previous array becomes:
[
{
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"
}
];
The array was reduced from 1 because it had a duplicate and the two values ββthat do not match are concatenated and separated by a comma type:"1,2"
.
I thought the following would work:
jQuery.each( data, function( i, val ) {
var productID = val.product_id;
var index_key = i;
jQuery.each( data, function( i, val ) {
if(val.product_id == productID && data[index_key] != data[i]){
jQuery.extend(data[index_key], data[i]);
}
});
});
But this only overwrites the type
first beat value and keeps both entries.
For "replaceable" elements, the values ββof prod_name
and are product_id
always the same.
Does anyone know a way to achieve the desired result?
UPDATE: Various values ββ(product attributes) can be added at a later stage. So I would prefer a method that does not specifically check for the attribute type
, but rather checks for the presence of eveything that is not product_id
or prod_name
, and if it has a hit, concatenate it with a comma.
source to share
What I am doing in the example below. First I create an object to achieve unique values ββ(via project_id
) and then convert the object to an array. In the first loop I check if there is an element in res
- put in res
, otherwise I only change the type of the property
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);
source to share