Javascript check if an id is present in an array of objects

Here my array :

[{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}]

I try to return true or false if an id is present in this array :

array.includes(2) -> true
array.includes(7) -> false

I need to do this on the id index of each object of the array.

I know i can use a foreach on each id of the array, but i want to use a cleanest way to do this.
What can i use ? Thanks !

18 thoughts on “Javascript check if an id is present in an array of objects”

  1. You can use below code :

        var array = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}]
        let isFind = array.findIndex((item,index)=>item.id===yourID)
        if(isFind !==-1){
          //means your id is in array
          return true
        }else{
          //not present in array
          return false
        }
    

    OR

    array.some(item => item.id === yourID)
    

    Thanks!

    Reply
  2. You can use Array.some():

    let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];
    arr.some(e => e.id === 1);
    // -> true
    

    If you want an approach like arr.includes() you can extend the Array prototype:

    let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];
    
    Array.prototype.hasId = function(id){
        return this.some(e => e.id === id);
    };
    
    console.log(arr.hasId(1));
    console.log(arr.hasId(3));
    console.log(arr.hasId(4));

    Otherwise I’d just wrap it inside a function:

    let arr = [{id: 1, value:'blabla'}, {id: 2, value:'blabla'}, {id: 3, value:'blabla'}];
    
    
    let hasId = function(arr, id){
        return arr.some(e => e.id === id);
    };
    
    console.log(hasId(arr, 1));
    console.log(hasId(arr, 2));
    console.log(hasId(arr, 4));
    Reply

Leave a Comment