Skip to content
Advertisement

Remove duplicate objects from JSON file in JavaScript

This is the current JSON file:

[{
    "name": "Peter",
    "age": 30,
    "hair color": "brown"
}, {
    "name": "Steve",
    "age": 55,
    "hair color": "blonde"
}, {
    "name": "Steve",
    "age": 55,
    "hair color": "blonde"
}]

I want to remove the duplicate Steve individual from the list. How can I make a new JSON that checks if the object’s name matches and remove any duplicates in JavaScript?

Advertisement

Answer

You must load the JSON data in to the program and parse that with JSON.parse, like this

var array = JSON.parse(content.toString())

To filter out the repeated names from the array of Objects, we use Array.prototype.filter function. You can store the names in an object, and next time when the same name appears we simply filter it out from the result.

var seenNames = {};

array = array.filter(function(currentObject) {
    if (currentObject.name in seenNames) {
        return false;
    } else {
        seenNames[currentObject.name] = true;
        return true;
    }
});

console.log(array);
# [ { name: 'Peter', age: 30, 'hair color': 'brown' },
#   { name: 'Steve', age: 55, 'hair color': 'blonde' } ]
Advertisement