0

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"]
    }
]
1
  • Seems like you are looking for a forEach loop? From you example, [...new Set(events.flatMap(({tags}) => tags))].sort().forEach((tag) => { // do what you would like to do with unique tags console.log(item) ) } Commented Feb 22, 2022 at 23:31

1 Answer 1

1
export default function App() {
  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"]
    }
  ];  
  const result = [...new Set(events.flatMap(({tags}) => tags))].sort();
  return (
    <div>
      {
        result.map((tag,i) => <h1 key={i}>{tag}</h1>)
      }
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

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.