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?
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>
)
If I got it right, I guess you can do the same using map itself
Assume you have the below array
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",
]
}]
and now you wanna just pull out the answers key alone then you can do something like
const result = questions.map((question) => {answers: question.answers}); // where the specific key here is answers