0

I want to find the questionOption.title === "Ubication" but I cannot access in the properties of question_option_history.questionOption and I don't know why. This is an example: The code:

const dataToFind = locationQuestion.question_option_history;

And this is the response:

[
{
    "id": 234,
    "answer": "Juan's house",
    "questionOption": {
        "id": 8,
        "title": "Ubication details:"
    }
},
{
    "id": 233,
    "answer": "30.888,-10.111",
    "questionOption": {
        "id": 7,
        "title": "Ubication:"
    }
}]

So, when I do question_option_history.questionOption.title VSCode give me an error telling

title doesn't exist in QuestionOption[]

(QuestionOption y the entity).

I want to run the array and find what is the questionOption.title === "Ubication" and take the answer of that object. Because in that object I save the lat and long of the ubication.

This is what I want to do:

let dataToFind = locationQuestion.question_option_history.find(option => option.questionOption.title === "Ubication");

And take the answer of dataToFind, to save the coordinates

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Pato
  • 3
  • 2
  • "This is what I want to do:" Have you tried doing that? – Heretic Monkey Aug 17 '23 at 19:07
  • Not sure how to help, bruh. Is the error occurring on the auto-complete? or when you execute your code? Your code snippets are not painting a clear picture - how about you demonstrate with a codepen. – Zxeenu Aug 17 '23 at 19:15
  • I fix finally, the error was in the relations between the entities. Thanks guys! – Pato Aug 17 '23 at 19:23

1 Answers1

0
type QuestionOptionWithTitleAndId = {id: number; title: string}
type ExtendedQuestionOption = QuestionOption & {questionOption: QuestionOptionWithTitleAndId}
const dataToFind = locationQuestion.question_option_history as ExtendedQuestionOption;

What you are trying to do is access a property on an object which is not defined inside of the type definition of the object.

In order to tell typescript that the property will actually exist on the object you can either add this directly to your QuestionOption type or, in case this QuestionOption comes from a library, create a new type by extending the QuestionObject type.

Then you can declare your dataToFind as this new type, so typescript will know that questionOption.title and questionOption.id will always be available. Afterwards, it should let you access them properly, and the suggested code (on the bottom of your question) should work fine.

Throvn
  • 795
  • 7
  • 19