'Problem using .find to manipulate an array of objects in javascript
I have been trying to get this solved for a while, but can't figure it out. I received some products from an API and after deconstructing, I passed them into some HTML tags to perform DOM manipulation on them from JS like so...
displayProducts(products){
let result = '';
products.forEach(product => {
result += `
<article class="product">
<div class="img-container">
<img src=${product.image} alt="product" class="product-img">
<button class="bag-btn" data-id= ${product.id}>
<img src="./images/icons8_add_shopping_cart_100px.png"
width="16px" max-width= "18px" alt="add to cart"/>
Add to cart
</button>
</div>
<div class="goodsinfo">
<span class="description"> <img src="./images/icons8_eye_100px.png" class="view" data-class=${product.id}/>
</span>
<span class="titleprice">
<h3>${product.title}</h3>
<h4>#${product.price}</h4>
</span>
</div>
</article>
`
});
productsDOM.innerHTML = result;
}
Then I started manipulating, but I ran into a problem using the .find array method to match an id with the id from the array of objects even though they're exactly the same.
compileDescription(products){
console.log(products) // this works fine and displays 16 products which are 16 objects in arrays.
const eyeView = [...document.querySelectorAll('.view')];
eyeView.forEach(viewBtn=>{
viewBtn.addEventListener('click', (event)=>{
const btnId = event.target.dataset.class
console.log(btnId); //this works and shows the ID of the clicked button
const productFind = products.find(product=> product.id === btnId)
console.log(productFind); //returns undefined
})
})
}
What I want is that when a button with a particular id is clicked, the id is matched with an id of an object in the array of objects and the object is returned to me for manipulation. Please help me guys. Thanks ahead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
