0

I have a array as follows:

data = [
 {
  "tag":"A"
 },
 {
  "tag":"B"
 },
 {
  "tag":"C"
 }
];

I want these tags' values in another array. I know I can do it using forEach loop but want to do it in some other efficient way. Any way to do it?

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Roma
  • 23
  • 3
  • Does this answer your question? [From an array of objects, extract value of a property as array](https://stackoverflow.com/questions/19590865/from-an-array-of-objects-extract-value-of-a-property-as-array) – DedaDev Jan 20 '23 at 06:53

1 Answers1

0

It's best to use a .map() call for this instead of .forEach(). See the MDN article for .map()

data = [
 {
  "tag":"A"
 },
 {
  "tag":"B"
 },
 {
  "tag":"C"
 }
];

const tags = data.map(el => el.tag);
console.log(tags)

Rather than having to create a temporary array, the .map() function transforms each value in an existing array into a new array. In this case, you just take the .tag property of every old element to make the new element.

Michael M.
  • 10,486
  • 9
  • 18
  • 34