kennechu kennechu - 6 months ago 13
AngularJS Question

Avoid duplicated records in a key, value structure JS

An easy question from a noob.

I have this example where I create a list with a Key/Value structure, I use the Id as the Key and the rest of the content is the value so if I add more records they will be added to my list $scope.itemList [ ]

var data = [
{
id: 1,
name : "Peter",
lastname : "Smith",
age : 36
}, {
id: 2,
name : "Peter",
lastname : "Smith",
age : 36
}
];

$scope.itemList = [];
angular.forEach(data, function(item){
var obj = {};
var valObj = {};

valObj.name = item.name;
valObj.lastname = item.lastname;
valObj.age = item.age;

obj[item.id] = valObj;
$scope.itemList.push(obj);
});


The thing is that I could have more records in my json with the same id and I want to avoid adding duplicated records, now this code will push everything it comes in it without matter if the id's are duplicated, but I dont know how to compare the var obj {} with the item.id, I tried different "options" but none of them work.

Some help on this will be great and I'll appreciate it a lot

Answer

If you changed the itemList from a list to a dictionary, I think it would do what you need. Something like:

var data = [
              {
                id: 1,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }, {
                id: 2,
                name : "Peter",
                lastname : "Smith",
                age : 36
              }
            ];

            $scope.itemDictionary = {};
            angular.forEach(data, function(item){
                var obj = {};
                var valObj = {};

                valObj.name = item.name;
                valObj.lastname = item.lastname;
                valObj.age = item.age;

                obj[item.id] = valObj;
                if(!$scope.itemDictionary[item.id]){
                     $scope.itemDictionary[item.id] = obj;
                }
            });