0

Javascript code loop once only when do array.push when put console.log(odgovor) it display everything good

getTacni() {
    this.storageService.getQuestions().then(items => {
      let odgovori: { id: number; answer: number }[] = [];
      let odgovor: { id: number; answer: number } = { id: null, answer: null };
      for (let i of items) {
        odgovor.id = i.id;
        odgovor.answer = i.tacan;
        console.log(odgovor);
      }
    });
  }

FAIL every element in odgovori is same

getTacni() {
    this.storageService.getQuestions().then(items => {
      let odgovori: { id: number; answer: number }[] = [];
      let odgovor: { id: number; answer: number } = { id: null, answer: null };
      for (let i of items) {
        odgovor.id = i.id;
        odgovor.answer = i.tacan;
        odgovori.push(odgovor);
      }
    });
  }

2 Answers 2

4

In both snippets, you've only created one object in memory, which you proceed to mutate many times - create each object inside the loop instead:

getTacni() {
  this.storageService.getQuestions().then(items => {
    const odgovori: { id: number; answer: number }[] = [];
    for (let i of items) {
      const odgovor: { id: number; answer: number } = { id: i.id, answer: i.tacan };
      odgovori.push(odgovor);
    }
  });
}

You also might consider using .map, which is a concise, functional, and readable way to transform every element of one array into another:

getTacni() {
  this.storageService.getQuestions().then(items => {
    const odgovor = items.map(({ id, tacan }) => ({ id, answer: tacan }));
  });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

getTacni() {
  this.storageService.getQuestions().then(items => {
    const odgovori: { id: number; answer: number }[] = [];
    for (let i of items) {
      odgovori.push({ id: i.id, answer: i.tacan });
    }
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.