How to use forEach loop In Javascript
The forEach executes a provided function once for each array element. It does not return a new array. It is used to iterate through each ID in productIDs.ids and check if it exists in the productDetails object, pushing the corresponding product details into the matchingProducts array.
Example: Finding details of the products matching with IDs in the array using the forEach.
Javascript
// Object with product IDs const productIDs = { ids: [101, 102, 104, 105] }; // Separate object containing product details const productDetails = { 101: { name: "Laptop" , price: 999 }, 102: { name: "Smartphone" , price: 599 }, 103: { name: "Headphones" , price: 99 }, 104: { name: "Tablet" , price: 299 }, 106: { name: "Mouse" , price: 29 } }; // Function to find products by IDs using forEach function findProductsByID(productIDs, productDetails) { const matchingProducts = []; productIDs.ids.forEach(id => { if (productDetails.hasOwnProperty(id)) { matchingProducts.push(productDetails[id]); } }); return matchingProducts; } // Find products by IDs const matchingProducts = findProductsByID(productIDs, productDetails); console.log( "Matching products:" , matchingProducts); |
Output
Matching products: [ { name: 'Laptop', price: 999 }, { name: 'Smartphone', price: 599 }, { name: 'Tablet', price: 299 } ]
How to find Objects Containing Matching Elements from Arrays in Another Object ?
The task is to find objects that contain matching elements from arrays in another object. An object containing an array of values and a separate object. The objective is to determine whether the values present in the array are also present as keys in the separate object.
These are the following methods:
Table of Content
- Using forEach loop
- Using filter() and map() method
- Using reduce() method
Contact Us