My data is stored in a nested structure as following:
let myElement = {
answer: { 0: "yes", 1: "no"},
properties: {
question: { 0: "cloudy", 1: "rainy"}
}
}
I need to get the list of questions, and achieved it by:
Object.entries(myElement.answer).forEach(([answerIndex]) => {
Object.entries(myElement.properties.question).forEach(([questionIndex, questionValue]) => {
if (answerIndex == questionIndex) {
console.log("question: ", questionValue);
}
})
});
However, I would like to avoid using two loops. Instead, I would like to use a code like the following (the number of questions and answers are always the same):
Object.entries(myElement.answer).forEach(([answerIndex]) => {
console.log("question: ", myElement.properties.question[answerIndex]);
});
But I get the error:
Element implicitly has an 'any' type because expression of type 'string' can not be used
to index type '{ 0: string; 1: string; }'.
No index signature with a parameter of type 'string' was found on type
'{ 0: string; 1: string; }'.ts(7053)
I noticed that if I change my question to list (... question: [ 0: "cloudy", 1: "rainy"] ...
) this error is gone, but unfortunately I can’t change the structure of data.
Is there anyway I avoid using two loops?