How to check if values in array is present in object key of object array

I want to check if values in one array is present in object key of object array.
For example: arr = ["id1", "id2"]

objectArr = [{id: "id1"}]

I want to throw not found error in this case when id2 is not present in id of object array.
Help of any kind would be appreciated!

19 thoughts on “How to check if values in array is present in object key of object array”

  1. It sounds like what you’re looking for is .every() method. You can loop through each element in your array and test if they are present in the other array.

    const allElementsFound = ["id1", "id2"].every(el => objectArr[id].includes(el))
    if(!allElementsFound) {
        // throw error 
    }
    
    Reply
  2. You can try something like this

    var arr = ["id1", "id2", "id3", "id4"];
    var n = arr.includes("id2"); //true
    

    For an array of objects. If the id is unique in the array

    var arr = [{id:"id1"},{id:"id2"},{id:"id3"},{id:"id4"}]
    const found = arr.some(el => el.id === "id3") // true
    
    Reply
  3. If You iterate over objectArr, You can get object fields in form of array with: Object.entries(your_object).

    for (const obj of objectArr) {
        for (const item of Object.entries(obj)) {
            // where item is field in object
            // now You can compare if item is in [id1,id2]
        }
    }
    
    
    Reply
  4. isAllPresent = arr.includes(objectArray.map(obj => Object.values(obj))) // will return true if every item on arr is present in objArr's objects. else returns false.
    

    If you want to make sure every item on arr is present in the objectArr’s objects as values, you can use this, Array.every() method.

    Reply

Leave a Comment