Not sure what you are trying to achieve, but it looks like you get an array of objects from the backend and you want to turn it into an array of objects, but with different property names. That’s a simple Array.prototype.map()
:
const response = await fetch(url);
const data = await response.json();
const questions = data.map((question) => {
return {
id: question.numb,
question: question.text,
options: question.choices,
};
});
If you are just trying to create some kind of centralized state manager / store that would also implement accessors to that data, then the main issue is you are passing properties one by one; instead, you should just call add
once per item (question):
function mockedFetch() {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
json: () => Promise.resolve([{
numb: 1,
text: 'Q1',
choices: ['Q1-A', 'Q1-B'],
}, {
numb: 2,
text: 'Q2',
choices: ['Q2-A', 'Q2-B'],
}]),
});
}, 1000 + 2000 * Math.random());
});
}
class QuestionStore {
data = [];
addQuestion(question) {
this.data.push(question);
}
getQuestion(id) {
return this.data.find(q => q.id === id);
}
getQuestions() {
return this.data;
}
}
const questionStore = new QuestionStore();
async function getData(){
const response = await mockedFetch();
const data = await response.json();
data.map((question) => {
questionStore.addQuestion({
id: question.numb,
question: question.text,
options: question.choices,
});
});
console.log(questionStore.getQuestions());
console.log(questionStore.getQuestion(1));
}
getData();
.as-console-wrapper {
max-height: 100% !important;
}
However, I think that’s not the case and this might just be some kind of confusion.
1
solved JAVASCRIPT DICTIONARY CREATION DYNAMICALLY