Remove duplicate objects from JSON file in javascript

By | December 12, 2019

So here is how we can remove the duplicate objects from json file using javascript,

[
{
    "Id": "12345",
    "Name": "Jatin"
}, 
{
    "Id": "12346",
    "Name": "Ajay"
}, 
{
    "Id": "12345",
    "Name": "Jatin"
}, 
]

Now i need to remove duplicate records [whose id matches] from above json file,

1) we need to parse json file using json.parse method as below,

var empDetailsArray = JSON.parse(jsondata.toString());

Now we have all the json data into empDetailsArray array [its a array of objects] . To filter out duplicate records we have to use filter method of array as below,

var FilteredEmpObjects = {};

filteredRecords = empDetailsArray.filter(function(empObject) {
    if (empObject.Id in empDetailsArray) {
        return false;
    } else {
        FilteredEmpObjects[empObject.Id] = true;
        return true;
    }
});