1

I have an an array of tags linked to an article which contains nested objects:

[ {id: 1, name: {"en": "Tag 1" }}, {id: 2, name: {"en": "Tag 2" }}, {id: 3, name: {"en": "Tag 3" }} ]

I want to create a new array which simply shows the tag name is a single array:

[Tag 1, Tag 2, Tag 3]

I created the following method:

var tagNames = [];
  this.article.tags.forEach(value => {
    tagNames.push(Object.values(value["name"]));
  });
console.log(tagNames);

However, this creates an array of arrays:

[[Tag 1],[Tag 2],[Tag 3]]

How can I achieve the single array I want?

Button89
  • 11
  • 1
  • 3

3 Answers3

1

you can replace :

tagNames.push(Object.values(value["name"]));

by

tagNames = [...tagNames,...Object.values(value["name"])];
Wandrille
  • 6,267
  • 3
  • 20
  • 43
0

You could use map() to do that.

let data = [ {id: 1, name: {"en": "Tag 1" }}, {id: 2, name: {"en": "Tag 2" }}, {id: 3, name: {"en": "Tag 3" }} ];

let tags = data.map(item => item.name.en);

console.log(tags);

Object.values() creates an array of values. So, in your code you could use flat() to convert the result to desired format.

let data = [ {id: 1, name: {"en": "Tag 1" }}, {id: 2, name: {"en": "Tag 2" }}, {id: 3, name: {"en": "Tag 3" }} ];

var tagNames = [];

data.forEach(value => {
  tagNames.push(Object.values(value["name"]));
});

console.log(tagNames.flat());
Nikhil
  • 6,493
  • 10
  • 31
  • 68
0

You could destructure the object and take en only for mapping.

var data = [{ id: 1, name: { en: "Tag 1" } }, { id: 2, name: { en: "Tag 2" } }, { id: 3, name: { en: "Tag 3" } }],
    result = data.map(({ name: { en } }) => en);

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392