So, I have a array with multiple objects with multiple properties:
JavaScript
x
18
18
1
let myArr = [{
2
id: 1,
3
x: 120,
4
y: 150,
5
}, {
6
id: 2,
7
x: 170,
8
y: 420,
9
}, {
10
id: 3,
11
x: 160,
12
y: 220,
13
}, {
14
id: 4,
15
x: 140,
16
y: 170,
17
}];
18
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:
JavaScript
1
4
1
if(myArr[0].id == myVar){
2
//do something
3
}
4
but this for each object in my array
Advertisement
Answer
Try like this
JavaScript
1
23
23
1
let myArr = [{
2
id: 1,
3
x: 120,
4
y: 150,
5
}, {
6
id: 2,
7
x: 170,
8
y: 420,
9
}, {
10
id: 3,
11
x: 160,
12
y: 220,
13
}, {
14
id: 4,
15
x: 140,
16
y: 170,
17
}];
18
19
let myVar = 1;
20
21
const found = myArr.find(element => element.id === myVar);
22
23
console.log(found)