Why keys of object is just first character?

Viewed 189

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);
  }

1 Answers

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);
  }

Related