How to map over an array in JavaScript?
Asked 5/20/2024Viewed 1,502 times
128
I have an array of objects and I want to transform it into an array of strings, extracting a specific property from each object. What is the most idiomatic way to do this in JavaScript? I have tried a for loop but it feels verbose.
javascript const data = [{id: 1, name: "apple"}, {id: 2, name: "banana"}]; // desired output: ["apple", "banana"]
javascript const data = [{id: 1, name: "apple"}, {id: 2, name: "banana"}]; // desired output: ["apple", "banana"]
javascript
arrays
es6
AL
askedabout 1 year ago
AliceWonder1,250
2 Answers
15
To solve this, you should use the `Array.prototype.map()` method. It creates a new array populated with the results of calling a provided function on every element in the calling array.
BO
answeredabout 1 year ago
BobTheBuilder870
8
Another approach could be a `for...of` loop if you need more control or are dealing with asynchronous operations inside the loop.
CH
answeredabout 1 year ago
CharlieCode2,400
Your Answer