2

How to get values listed in translations object?

I am trying to use Array destructuring to get object values.

Even while getting keys javascript won't return full key value such as getaQuote instead it turns out just first letters g.

Expected console result would be:

getaQuote : a : Get a Quote: Kostenloses Angebot : Richiedi un preventivo : Teklif Al
uploadFile : b : Upload File: Datei Upload : Datei Upload : Dosya Gönder

"use strict";

const translations = {
  getaQuote: {
    loc: "a",
    en: "Get a Quote",
    de: "Kostenloses Angebot",
    it: "Richiedi un preventivo",
    tr: "Teklif Al"
  },
  uploadFile: {
    loc: "b",
    en: "Upload File",
    de: "Datei Upload",
    it: "Datei Upload",
    tr: "Dosya Gönder"
  },
  contacts: { loc: "c", en: "Contacts", de: "Kontakt", it: "Contatti" , tr: "İletişim"}
};
  for (let  [key, value] in translations ) {
    let result = `${key}: ${value.loc} : ${value.en} : ${value.de} : ${value.it}:  ${value.tr}`;
    console.log(result);
  }
Cem Kaan
  • 2,086
  • 1
  • 24
  • 55
  • `(let [key, value] in translations )` - the `for..in` loop goes over *keys*, so you get each key and then destructure the first two characters of it. First, you want a `for..of` loop and second, you want to iterate over `Object.entries(translations)` – VLAZ Oct 10 '20 at 08:32
  • See also [What is the difference between ( for… in ) and ( for… of ) statements in JavaScript?](https://stackoverflow.com/q/29285897) | [JavaScript for…in vs for](https://stackoverflow.com/q/242841) – VLAZ Oct 10 '20 at 08:36

1 Answers1

2

You get the keys from the object by using a for ... in statement, but the string is destructured with the first two characters.

A destructuing of a string calls the implemented iterator and returns the characters.

const [key, value] = 'get';

console.log(key);
console.log(value);

To overcome this, you could iterate the entries of the object and get the destructured pairs with an for ... of statement.

"use strict";

const translations = {
  getaQuote: {
    loc: "a",
    en: "Get a Quote",
    de: "Kostenloses Angebot",
    it: "Richiedi un preventivo",
    tr: "Teklif Al"
  },
  uploadFile: {
    loc: "b",
    en: "Upload File",
    de: "Datei Upload",
    it: "Datei Upload",
    tr: "Dosya Gönder"
  },
  contacts: { loc: "c", en: "Contacts", de: "Kontakt", it: "Contatti" , tr: "İletişim"}
};
  for (let  [key, value] of Object.entries(translations)) {
    let result = `${key}: ${value.loc} : ${value.en} : ${value.de} : ${value.it}:  ${value.tr}`;
    console.log(result);
  }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392