Javascript Question

Angularjs:Remove duplicate property, but get our value

Output of console.log() is given below. I want to remove duplicate "characteristic", but get our "value".

This is my foreach for make result from below code:

angular.forEach(checkCharacteristicValue, function(item) {
console.log(item)
$scope.allCharAndValue.push({
characteristic: item.businessassetcharacteristic.characteristicName,
value: item.characteristicValue
});
});


Output:

Object 1:
characteristic: "Вид Маса"
value: "2-ни"
__proto__: Object
Object 2:
characteristic: "Вид Маса"
value: "4-ни"
__proto__: Object
Object 3:
characteristic: "Вид Маса"
value: "6-ни"
__proto__: Object


I want to see this result:
{ name:Вид Маса, value:["2-ни", "4-ни", "6-ци"] }

Answer

This is how i'll do it.

I use an object to store the same characteristic items and create an array with all the values for that key. Try it and tell me if it is ok for you ;)

var raw = [{
  characteristic:    "Вид Маса",
  value:    "2-ни"
},
{
characteristic:    "Вид Маса",
value:    "4-ни"
},
{
characteristic:    "Вид Маса",
value:    "6-ни"
}];

// dedup 
var dedup = {};
raw.forEach(function(e,i) {
  if (! dedup.hasOwnProperty(e.characteristic) ) {
        dedup[e.characteristic] = { name : e.characteristic };
        dedup[e.characteristic].value = [];
  }
  dedup[e.characteristic].value.push(e.value);
});

// flatten to fit requirements
var flatten = [];
for(var key in dedup) {
  flatten.push(dedup[key]);
}

console.log(flatten);