How to Pluck Data from an Array of Objects in JavaScript?

Estimated read time 2 min read

To pluck data from an array of objects in JavaScript, you can use the map() method to create a new array containing only the desired properties of each object. Here’s an example:

let people = [
  { name: "John", age: 30, occupation: "Developer" },
  { name: "Jane", age: 25, occupation: "Designer" },
  { name: "Bob", age: 40, occupation: "Manager" }
];

let names = people.map(person => person.name);

console.log(names); // outputs ["John", "Jane", "Bob"]

In this example, we define an array of people objects, each containing name, age, and occupation properties. We then use the map() method to create a new array containing only the name property of each object. The resulting names array contains the names of all the people.

You can also use object destructuring within the map() method to pluck multiple properties from each object. For example:

let peopleData = people.map(({ name, age }) => ({ name, age }));

console.log(peopleData); // outputs [{ name: "John", age: 30 }, { name: "Jane", age: 25 }, { name: "Bob", age: 40 }]

In this example, we use object destructuring within the map() method to pluck the name and age properties of each object. We then create a new object containing only those properties and return it as the result of the map() method. The resulting peopleData array contains objects with only the name and age properties of each person.

You May Also Like

More From Author

2Comments

Add yours

Leave a Reply