Reputation: 644
I have an array of objects
myArrayOfObjects = [
0: {
title: 'title 1',
ids: ['90b7f1804642', 'ffa339e9aed7']
},
1: {
title: 'test 2',
ids: ['99472a9cb432', 'ec3d70ea6ef8']
}
];
I want to check each of the values in ids array if they match an id I have outside. This is what I came up with:
myArrayOfObjects.forEach((item, index) => {
if(item.ids[index] === this.myId) {
console.log('SUCCESS');
}
})
But it does not go through all of the values in ids array. What is the appropriate way to solve this?
Upvotes: 0
Views: 75
Reputation: 641
The index
you're using there is the index of the current item that the forEach is on, not an index in the ids array. You could do another forEach on that ids array, or just a .includes looks nicer, I think:
myArrayOfObjects.forEach((item, index) => {
if(item.ids.includes(this.myId)) {
console.log('SUCCESS');
}
})
Upvotes: 1
Reputation: 1487
Please try:
myArrayOfObjects.forEach((item, index) => {
if(item.ids.includes(this.myId)) {
//or if(item.ids.indexOf(this.myId) > -1) {
console.log('SUCCESS');
}
})
Upvotes: 0
Reputation: 6844
You need to loop over the array inside the array
myArrayOfObjects.forEach((item) => {
item.ids.forEach((id) => {
if(id === this.myId) {
console.log('SUCCESS');
}
});
})
Upvotes: 0