React: How do I use values from an object’s specific key? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React: How do I use values from an object’s specific key? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am new to React and am trying to figure out how to return a particular objects entry by it’s key.

So far, I have an object as such:

const questions = [
  {
    id: '1',
    section: 's1',
    answers: [
      "answer a",
      "answer b",
      "answer c",
      "answer d",
    ]
  },
  {
    id: '2',
    title: 'Question 2',
    answers: [
      "answer a",
      "answer b",
      "answer c",
      "answer d",
    ]
  },
  //etc

which I am currently iterating through and using parts of as props in a component, eg:

  return (
    <div>
      {questions.map((question) => (
        <Question
          key={question.id}
          questionNum={question.id}
          title={question.title}
          answers={question.answers}
        />
      ))}
    </div>
  );

This works fine and as expected.

But now I need to modify this so it only returns the values of 1 given particular key in the object.

I’ve been searching and experimenting with .get() but to be honest I’m really stumped with how to do this.

Would anyone know the best way to approach this?

Answer

You can filter the questions by a particular key of the object first and then do the map. Let’s say id with value 1.

return (
    <div>
        {questions
            .filter(({ id }) => id === "1")
            .map(question => (
                <Question
                    key={question.id}
                    questionNum={question.id}
                    title={question.title}
                    answers={question.answers}
                />
            ))}
    </div>
)
We are here to answer your question about React: How do I use values from an object’s specific key? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji