Search code examples
javascriptnode.jsunderscore.jslodash

How to get the Uniq objects Using javascript or lodash


i am having the Array of objects like this

    var result={
            "employees": [
        {
            "_id": "5796e7a27d075bd0453b7751",
            "firstName": "Test4",
            "schemaName": "Employee"
        },
        {
            "_id": "5796e78e7d075bd0453b774f",
            "firstName": "Test 3",
            "schemaName": "Employee"
        },
        {
            "_id": "5790b203df5ad69025e8a20b",
            "email": "[email protected]",
            "schemaName": "Employee"
        },
        {
            "_id": "577f69cc789df5ec1e995513",
            "firstName": "Jeevan",
            "email": "[email protected]",
            "schemaName": "Employee"
        },
        {
            "_id": "577f69cc789df5ec1e995513",
            "firstName": "Chethan",
            "email": "[email protected]",
            "schemaName": "Employee"
        }
    ]
};
    };

but i want uniq objects by email. i am using lodash uniq but its Not giving proper Result. here i tried this code.

var combined=result.employees.map(function(employee){
    employee.schemaName='Employee';
    return employee;
});
combined = _.uniq(combined, 'email');
console.log(combined);

The Result is coming like this.

   [ { _id: '5796e7a27d075bd0453b7751',
    firstName: 'Test4',
    schemaName: 'Employee' },
  { _id: '5790b203df5ad69025e8a20b',
    email: '[email protected]',
    schemaName: 'Employee' },
  { _id: '577f69cc789df5ec1e995513',
    firstName: 'Jeevan',
    email: '[email protected]',
    schemaName: 'Employee' } ]

i want the objects which are not having email ids and i want only objects which are unique emailid's can anybody help me on this. I want the Result contain the objects Which are not having email id also. The Result should be like this.

[ { _id: '5796e7a27d075bd0453b7751',
    firstName: 'Test4',
    schemaName: 'Employee' },
{ _id: '5796e78e7d075bd0453b774f',
    firstName: 'Test3',
    schemaName: 'Employee' },
  { _id: '5790b203df5ad69025e8a20b',
    email: '[email protected]',
    schemaName: 'Employee' },
  { _id: '577f69cc789df5ec1e995513',
    firstName: 'Jeevan',
    email: '[email protected]',
    schemaName: 'Employee' } ]

Solution

  • This could make it too.

    _.uniqBy(result.employees, function(employee){return employee.email || employee._id;});