0

I'm a JS beginner and I'm stuck with array/objects items. I get a JSON file with a fetch request and I would like to extract a part of the data.

My data looks like this:

{
"profil": [
 {
  "name": "",
  "id": ,
  "city": "",
  "country": "",
  "tags": ["", "", "", ""],
  "text": "",
  "price":
 },

So it's an object, which contain an array which contain a bunch of objects which contain a "tags" array....

I don't find a way to access tags items (without array index) with forEach loops... My final purpose with this is to collect a single list of tags that exists in my object list.

How can I do this?

1 Answer 1

2

Using Array#flatMap:

const data = {
  "profil": [
    { "tags": ["1", "2", "3", "4"] },
    { "tags": ["5", "6", "7", "8"] }
  ]
};

const tags = data.profil.flatMap(({ tags = [] }) => tags);

console.log(tags);

Edit: if you need the tags to be unique, you can use Set:

console.log([...new Set(tags)]);
Sign up to request clarification or add additional context in comments.

2 Comments

Run it through a Set because the tags can have duplicates
Thanks a lot. I added forEach(+if) condition to exclude repetition and all is good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.