Mauro Mauro - 3 months ago 12
Javascript Question

Extract properties from deleted/duplicated objects then asign to other objects

I need a little help here, y have this array:

[
{Code:13938, Country:699, Name:"Crocs", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:14}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:3}
{Code:13953, Country:699, Name:"OZ", codeProduct:12}
....
]


And I need to convert to this:

[
{Code:13938, Country:699, Name:"Crocs", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:"14, 1, 3" }
{Code:13953, Country:699, Name:"Polo Club", codeProduct:12}
]


I have no problem removing the duplicate objects, and getting the values of those delted objects.

var prodArray = [];

function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for(var i = 0; i < len; i++) {
var item = a[i].Codigo;
if(seen[item] !== 1) {
seen[item] = 1;
out[j++] = a[i];
}else{
prodArray.push({Code:item, codeProduct:a[i].TipoProductoCodigo});
}
}
return out;
}


this return a new array of objects whitout the repited values and add to a new array
prodArray
the properties of deleted ones.

// out return this:
[
{Code:13938, Country:699, Name:"Crocs", codeProduct:1}
{Code:13952, Country:699, Name:"Polo Club", codeProduct:"14, 1, 3" }
{Code:13953, Country:699, Name:"Polo Club", codeProduct:12}


]

and
prodArr
return this:

[
{Code:13952, codeProduct:1}
{Code:13952, codeProduct:3}
]


But how do i set the properties in
prodArray
in to the new one array that holds the no duplicate objects?.

Hope i have been clear

Answer

You could use a hash table as reference to the Code.

var data = [{ Code: 13938, Country: 699, Name: "Crocs", codeProduct: 1 },  { Code: 13952, Country: 699, Name: "Polo Club", codeProduct: 14 }, { Code: 13952, Country: 699, Name: "Polo Club", codeProduct: 1 }, { Code: 13952, Country: 699, Name: "Polo Club", codeProduct: 3 }, { Code: 13953, Country: 699, Name: "OZ", codeProduct: 12 }],
    grouped = [];

data.forEach(function (a) {
    if (!this[a.Code]) {
        this[a.Code] = { Code: a.Code, Country: a.Country, Name: a.Name, codeProduct: a.codeProduct };
        grouped.push(this[a.Code]);
        return;
    }
    this[a.Code].codeProduct += ', ' + a.codeProduct;
}, Object.create(null));
console.log(grouped);