Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

how to use arrow function to retrive data using foreach from objects or array in javascript

To retrieve data using forEach() and arrow functions from an array or object in JavaScript, you can follow these steps:

1.Create an array or object that contains the data you want to retrieve.
2.Use the forEach() method to loop through the array or object.
3.Inside the forEach() method, use an arrow function to access the elements of the array or object.
4.Use the arrow function to perform any desired actions with the retrieved data.
Here's an example that demonstrates how to use an arrow function with forEach() to retrieve data from an array:

const myArray = [1, 2, 3, 4, 5];

myArray.forEach((element) => {
  console.log(element);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we have an array called myArray that contains the numbers 1 through 5. We use the forEach() method to loop through the array, and we pass an arrow function as an argument to the forEach() method. The arrow function takes one parameter (element) that represents each element of the array as it is iterated over.

Inside the arrow function, we simply log the value of each element to the console. This code will output the following to the console:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Here's another example that demonstrates how to use an arrow function with forEach() to retrieve data from an object:

const myObject = {
  name: "John",
  age: 30,
  city: "New York",
};

Object.keys(myObject).forEach((key) => {
  console.log(key + ": " + myObject[key]);
});
Enter fullscreen mode Exit fullscreen mode

In this example, we have an object called myObject that contains some personal information. We use the Object.keys() method to get an array of the keys of the object, and then we use the forEach() method to loop through that array.

Inside the arrow function, we use the key to access the value of each property of the object and log it to the console. This code will output the following to the console:

name: John
age: 30
city: New York
Enter fullscreen mode Exit fullscreen mode

I hope this helps! Let me know if you have any further questions

===============================================================

Image description

output

Image description

Top comments (0)