Extract value of a property as array from an array of objects in JavaScript

In this tutorial, I will show you how you can extract the value of a property as an array from an array of objects in JavaScript. We will use map() method and for loop to extract a property value as an array.

Using map() method

We can use the map() method and arrow function to create a new array containing the values of the specified property for each object in the original array.

Here is the JavaScript program below:

const array = [
  { name: 'Alison', age: 23 },
  { name: 'Butcher', age: 27 },
  { name: 'Rayan', age: 29 }
];

const names = array.map(user => user.name);

console.log(names);

In the above program, the map() method iterates over the elements in the array and applies the arrow function to each element.

The arrow function receives each object in the array as an argument and returns the value of the name property for that object.

Then, the map() method creates a new array containing the return values for each element and returns a new array.

Output:

[ 'Alison', 'Butcher', 'Rayan' ]

Extract value of a property as array from an array of objects: Using for loop

To extract the value of a property as an array from an array of objects using a for loop in JavaScript, we can iterate over the objects in the array and push the values of the specified property into a new array.

Here is the JavaScript program below:

const array = [
  { name: 'Alison', age: 23 },
  { name: 'Butcher', age: 27 },
  { name: 'Rayan', age: 29 }
];

const names = [];

for (let i = 0; i < array.length; i++) {
  names.push(array[i].name);
}

console.log(names);

The for loop iterates over the elements in the array and pushes the value of the name property for each object into the names array.

Output:

[ 'Alison', 'Butcher', 'Rayan' ]

Leave a Reply

Your email address will not be published. Required fields are marked *