How to Extract Values from an Array of Objects in JavaScript?

Estimated read time 1 min read

You can extract values from an array of objects in JavaScript using the map method or a for loop.

Here’s an example using the map method:

let arr = [{name: "John", age: 25}, {name: "Jane", age: 30}, {name: "Jim", age: 35}];

let names = arr.map(function(obj) {
  return obj.name;
});

console.log(names);
// Output: ["John", "Jane", "Jim"]

In the example, the map method is used to iterate over each object in the array, and it returns a new array containing the name property of each object.

Here’s an example using a for loop:

let arr = [{name: "John", age: 25}, {name: "Jane", age: 30}, {name: "Jim", age: 35}];

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

console.log(names);
// Output: ["John", "Jane", "Jim"]

In this example, a for loop is used to iterate over each object in the array, and the push method is used to add the name property of each object to a new array. The final result is an array containing the values of the name property of each object in the original array.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply