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?
CodePudding user response:
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)]);