I am looking to identify duplicates by country code and merge them into a single object
The array structure is:
[{...},{...}]
Objects
{Country_Code: "RU", Country: "Russia", Provider: "Shell1", Price: "0.123"},
{Country_Code: "EN", Country: "Russia", Provider: "Shell", Price: "0.76856"},
{Country_Code: "RO", Country: "Russia", Provider: "Shell", Price: "0.563"},
{Country_Code: "RU", Country: "Russia", Provider: "Shell2", Price: "0.90890"},
{Country_Code: "RU", Country: "Russia", Provider: "Shell3", Price: "0.90"}
I want to get an array of objects like this
[{Country_Code: "RU", Country: "Russia", Provider: "Shell1 - 0.123</br>Shell2 - 0.90890</br>Shell3 - 0.90", Price: "0.123"},
{Country_Code: "EN", Country: "Russia", Provider: "Shell", Price: "0.76856"},
{Country_Code: "RO", Country: "Russia", Provider: "Shell", Price: "0.563"}]
If I think the approach should be something like
var NewArr =[],NewObj ={};
data.forEach(function(dataItem,index) {
CC = dataItem.Country_Code;
counts[CC]= (counts[CC]||0) + 1; // Count duplicates
if(counts[CC]>1){
NewObj.Country_Code = dataItem.Country_Code;
NewObj.Country = dataItem.Country;
NewObj.Provider = dataItem.Provider + " - " + dataItem.Price + "</br>";
NewObj.Price = dataItem.Price;
NewArr[indexOfDup] = NewObj;
}else{
NewArr.push(data[index]);
}
});
This syntax is incorrect, so how can I correct it?