Search code examples
javascriptarraysobjectlodash

How can I check if an element exists in array of objects using lodash


Suppose I have the following array:

var users = [
    {id: 3, name: "sally"}
    {id: 5, name: "bob"}
    {id: 40, name: "joe"}
    {id: 67, name: "eve"}
    {id: 168, name: "bob"}
    {id: 269, name: "amanda"}
]

I need to run a loadash function that would return true if, for example name == "bob" exists in the array regardless of how many times it exists in the array.

I would like to know is if there is one function I could use, possible using lodash (not necessarily though) that would return true or false indicating the existence of an object in the target array.

Thanks


Solution

  • You can use the filter function to search through your array and find the object with the given name.

    var users = [
        {id: 3, name: "sally"},
        {id: 5, name: "bob"},
        {id: 40, name: "joe"},
        {id: 67, name: "eve"},
        {id: 168, name: "bob"},
        {id: 269, name: "amanda"},
    ];
    
    function find(name) {
        return !!users.find(x => x.name === name);
    }
    

    More about the filter function can be found here