So, I have a array with multiple objects with multiple properties:
let myArr = [{ id: 1, x: 120, y: 150, }, { id: 2, x: 170, y: 420, }, { id: 3, x: 160, y: 220, }, { id: 4, x: 140, y: 170, }];
Now I want to see if the property of one of the objects in my array matches a variable. But I dont know how to do that! I want to check if the value of property “id” in one of my objects matches my variable. Something like this:
if(myArr[0].id == myVar){ //do something }
but this for each object in my array
Advertisement
Answer
Try like this
let myArr = [{ id: 1, x: 120, y: 150, }, { id: 2, x: 170, y: 420, }, { id: 3, x: 160, y: 220, }, { id: 4, x: 140, y: 170, }]; let myVar = 1; const found = myArr.find(element => element.id === myVar); console.log(found)