Write a JavaScript Program to Extract Given Property Values from Objects as Array

When working with JavaScript, you might find yourself needing to extract specific property values from objects and store them in an array.

This can be useful for a variety of tasks, such as data processing or filtering.

Here’s a simple JavaScript program that demonstrates how to extract given property values from objects as an array:

const data = [
  { name: 'John', age: 30, occupation: 'Developer' },
  { name: 'Jane', age: 25, occupation: 'Designer' },
  { name: 'Bob', age: 40, occupation: 'Manager' },
  { name: 'Sarah', age: 35, occupation: 'Analyst' },
];

const getPropertyValues = (arr, prop) => {
  return arr.map(obj => obj[prop]);
};

const ages = getPropertyValues(data, 'age');
console.log(ages); // Output: [30, 25, 40, 35]

In this program, we define an array of objects called data, each containing properties such as name, age, and occupation.

We then define a function called getPropertyValues that takes two parameters: an array of objects (arr) and a string representing the property we want to extract (prop).

Inside the getPropertyValues function, we use the map method to iterate over each object in the input array and extract the value of the specified property. The resulting values are then returned as an array.

Finally, we call the getPropertyValues function with our data array and the string ‘age’ as arguments.

This extracts the age values from each object and stores them in a new array called ages, which is then printed to the console.

In conclusion, extracting property values from objects as an array is a simple task in JavaScript.