I am trying to loop through all unique values from a nested object. It seems like something like this should be easy, but I can't figure out how to do it.
I have tried this
const result = [...new Set(events.flatMap(({tags}) => tags))].sort()
And then when I echo out { result } I ultimately get the output of unique values. But I want to use these values in the application. Somehow wrap each value in a <button> or something.
Below is my test object. Each item has an array of tags, and I want to be able to dynamically list out all unique tags.
I'd be very grateful for any help here.
Thanks in advance.
const events = [
{
id: 1,
name: "Event 1",
tags: ["tag 1", "tag 2", "tag 3"]
},
{
id: 2,
name: "Event 2",
tags: ["tag 1", "tag 3"]
},
{
id: 3,
name: "Event 3",
tags: ["tag 1", "tag 3", "tag 2"]
},
{
id: 4,
name: "Event 4",
tags: ["tag 1", "tag 5", "tag 3"]
},
{
id: 5,
name: "Event 5",
tags: ["tag 3"]
},
{
id: 6,
name: "Event 6",
tags: ["tag 2", "tag 3"]
}
]
[...new Set(events.flatMap(({tags}) => tags))].sort().forEach((tag) => { // do what you would like to do with unique tags console.log(item) ) }