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?
const someObj = { key1: 'value1', key2: 'value2', key3: ['someArray'] };<-- Consider this object. Now,someObj.key1will get usvalue1. And,someObj.key3[0]will get ussomeArray. In your example,questions[0].idwill get the value1. Whilequestions[1].titlewill getQuestion 2. So on & so forth.questions.map(({title})=>{<Question title={title} />})questions.maptoquestions.filter(q => q.id === 1).mapto get the question with ID 1 for example.