0

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!

1
  • Are you interested in typescript solution? Where TS will throw a type error? Commented Feb 17, 2021 at 8:20

4 Answers 4

2

You can use filter and some for that:

var objectArr = [{id: "id1"}, {id: "id3"}]
var arr1 = ["id1", "id2"];
const notFounds = arr1.filter(el => !objectArr.some(obj => obj.id === el ));
console.log(notFounds); // ["id2"]

JS Array some:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

JS Array filter:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Sign up to request clarification or add additional context in comments.

Comments

0

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]
    }
}

Comments

0

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

Comments

0

EDIT: ran.t has a better answer that keeps track of which ids are not found.

It sounds like what you're looking for is .every() method. Which will allow you can check each element in the array passes a given condition.

You can combine this with the .some() method to check at least one object in the objectArr has id equal to your element

const allElementsFound = ["id1", "id2"].every(el => objectArr.some(obj => obj.id === el))
if(!allElementsFound) {
    // throw error 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.