Eulerz

Verstehen, wie die Welt funktioniert.

1/11

Modernes JavaScript · Destructuring für Profis

Eine Wetter-API antwortet

Echte Daten kommen selten flach daher. So könnte die Antwort eines Wetterdienstes aussehen:

const antwort = {
  ort: { name: "Hamburg", land: "DE" },
  aktuell: { temp: 11.5, wind: { kmh: 28, richtung: "NW" } },
  vorhersage: [{ tag: "Mo", max: 13 }, { tag: "Di", max: 9 }, { tag: "Mi", max: 10 }],
};

Du brauchst nur Ortsname, Temperatur und Windstärke. Statt dreimal antwort.aktuell.wind.kmh zu tippen, packst du verschachtelt aus – das Muster links spiegelt die Form der Daten:

const {
  ort: { name },
  aktuell: { temp, wind: { kmh } },
} = antwort;

console.log(name, temp, kmh); // Hamburg 11.5 28

Achtung: ort: ist hier nur ein Wegweiser. Eine Variable ort entsteht dabei nicht – nur name, temp und kmh.

Enterzum Fortfahren