Shinji
Shinji

Reputation: 101

how to loop through objects made out of object constructors?

function weatherStation(place) {
    this.name = place;
    this.regn = 0;
    this.vind = 0;
    this.temperatur = 0;
}

so basically, this function will create an object of the class weatherStation. I wonder that, when I have made many for example

    var so = new weatherStation("Sola");
    so.regn = regn;
    so.vind = vind;
    so.temperatur = temperatur;

    var va = new weatherStation("Valand");
    va.regn = regn;
    va.vind = vind;
    va.temperatur = temperatur;

    var si = new weatherStation("Sinnes");
    si.regn = regn;
    si.vind = vind;
    si.temperatur = temperatur;

how can i be able to loop through this all, because i would like to print them out into the html but, i don't want to print them out one by one, since there will be one time where i don't know how many i have.

and is there a way i can make a new object each time i click on a button without overwriting the last one?

Upvotes: 0

Views: 101

Answers (1)

D Lowther
D Lowther

Reputation: 1619

Added some actions to make the answer verifiable, but essentially you would want to push each created element into an array and then have something to render elements based on an array. Here this is all accomplished inside the event trigger, but you could easily pull the render function out if you needed it for multiple different array contexts.

// weather station object
function WeatherStation(place, regn = 0, vind = 0, temperatur = 0) {
    this.name = place;
    this.regn = regn;
    this.vind = vind;
    this.temperatur = temperatur;
}

// set up stations array
const weatherStations = [];
// get action and display elements
const addStation = document.querySelector('.add-station');
const container = document.querySelector('.data-holder');

// set event listener
addStation.addEventListener('click', e => {
  e.preventDefault();
  // text input
  const stationInput = document.querySelector('.station-name');
  
  if (stationInput.value.length === 0) { return }
  
  // create new station object and add to stations group
  weatherStations.push(new WeatherStation(stationInput.value));
  
  // render it all out
  container.innerHTML = '';
  const listItems = weatherStations
    .map(station => `<li>${station.name}</li>`)
    .join('');
  container.innerHTML = listItems;
  
  stationInput.value = '';
});
<section>
  <article>
    <input type="text" class="station-name" />
    <button class="add-station">Add</button>
  </article>
  
  <article>
    <ul class="data-holder"></ul>
  </article>
</section>

Upvotes: 1

Related Questions