Skip to content
the poor coder

javascript pluck from array of objects

Poor Man
Published
Reading time
2 min read
On this page

Javascript Pluck from Array of Objects#

As a web developer, I have come across situations where I needed to extract a value from an array of objects in JavaScript. This process is known as "pluck" or "pick" and is a common problem when working with data.

Method 1: Using the map() function#

The first method I will discuss is using the map() function to pluck the desired value from each object in the array. This method involves creating a new array by mapping each object to its desired value.

Text

const arr = [
  { name: 'John', age: 30 },
  { name: 'Sarah', age: 25 },
  { name: 'Bob', age: 40 }
];

const names = arr.map(obj => obj.name);

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

In this example, we have an array of objects with two properties: name and age. Using the map() function, we create a new array containing only the values of the name property in each object.

Method 2: Using the reduce() function#

The second method involves using the reduce() function to pluck the desired value from each object in the array. This method involves iterating over each object in the array and adding its desired value to an accumulator.

Text

const arr = [
  { name: 'John', age: 30 },
  { name: 'Sarah', age: 25 },
  { name: 'Bob', age: 40 }
];

const names = arr.reduce((acc, obj) => {
  acc.push(obj.name);
  return acc;
}, []);

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

In this example, we have an array of objects with two properties: name and age. Using the reduce() function, we create a new array containing only the values of the name property in each object.

Conclusion#

Both the map() and reduce() functions can be used to pluck values from an array of objects in JavaScript. The choice between these two methods depends on personal preference and the specific requirements of the task at hand.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC