Search code examples
javascriptobjectiterationconsole.logtemplate-literals

In Javascript, can you use template literals to console.log content from an object while iterating over it?


So I am less than 1 week into learning JS and I've been trying to find a solution but other than an answer involving functions and something to do with JSON.stringify (which I don't understand) I cannot seem to find one. Rather than using string concatenation when iterating over this object I want to use template literals to display specific information from each property. Is that possible?

pokemonList = [
  {name: 'Bulbasur', height: 70, weight: 15.2, type: ['grass','poison']},
  {name: 'Charmander', height: 60, weight: 18.7, type: ['fire']},
  {name: 'Squirtle', height: 50, weight: 19.8, type: ['water']}
];

for (let i=0; i < pokemonList.length; i++) {
  console.log(`${pokemonList.name[i]} ${pokemonList.height[i]}`);
};

Solution

  • You definitely can! You just need to change pokemonList.name[i] to pokemonList[i].name.

    The pokemonList is the one that has elements within it, so you use pokemonList[i] to access an element within it, and then pokemonList[i].name will give you the name property of that element.

    Here's the fixed code:

    pokemonList = [
      {name: 'Bulbasur', height: 70, weight: 15.2, type: ['grass','poison']},
      {name: 'Charmander', height: 60, weight: 18.7, type: ['fire']},
      {name: 'Squirtle', height: 50, weight: 19.8, type: ['water']}
    ];
    
    for (let i=0; i < pokemonList.length; i++) {
      console.log(`${pokemonList[i].name} ${pokemonList[i].height}`);
    };

    JSON.stringify on the other hand will print the entire object as a string, and it will look similar to how it looks in the list above within your code:

    pokemonList = [
      {name: 'Bulbasur', height: 70, weight: 15.2, type: ['grass','poison']},
      {name: 'Charmander', height: 60, weight: 18.7, type: ['fire']},
      {name: 'Squirtle', height: 50, weight: 19.8, type: ['water']}
    ];
    
    for (let i=0; i < pokemonList.length; i++) {
      console.log(JSON.stringify(pokemonList[i]));
    };