Is there a way to begin the Iteration process at 1 by utilizing the Object.entries() method in JavaScript?

const game = {
  team1: 'Real Madrid',
  team2: 'Barcelona',
  players: [
    [
      'Courtois',
      'Carvajal',
      'Ramos',
      'Varane',
      'Marcelo',
      'Casemiro',
      'Kroos',
      'Modric',
      'Vinicius',
      'Benzema',
      'Rodrygo',
    ],
    [
      'Ter Stegen',
      'Sergi Roberto',
      'Pique',
      'Lenglet',
      'Jordi Alba',
      'Busquets',
      'De Jong',
      'Pedri',
      'Messi',
      'Dembele',
      'Griezmann',
    ],
  ],
  score: '3:1',
  scored: ['Benzema', 'Benzema', 'Vinicius', 'Messi'],
  date: 'Dec 25th, 2037',
  odds: {
    team1: 1.55,
    x: 3.0,
    team2: 5.0,
  },
};

1) Iterate through the game.scored array and display each player's name on the screen along with the goal number starting from 1 (Goal 1: etc)

This is my preferred solution which gives me the desired output:

for (const [i, v] of game.scored.entries()) 
{
  console.log(`Goal: ${i + 1} ${v}`);
}

Output:

Goal: 1 Benzema

Goal: 2 Benzema

Goal: 3 Vinicius

Goal: 4 Messi

Result Display:

However, I encountered an issue when attempting a different approach using Object.entries() as it did not start the iteration from 1

Solution 2

for (const [i, v] of Object.entries(game.scored)) 
{
  console.log(`Goal: ${i+1} ${v}`);
}

Output:

Goal: 01 Benzema

Goal: 11 Benzema

Goal: 21 Vinicius

Goal: 31 Messi

Result Display:

Answer №1

The initial method involves extracting the array and its elements (Array#entries), while the second approach focuses on retrieving the object and its entries (Object.entries).

Objects typically have keys that are either strings or symbols. In order to process a number as a value, it must be converted into a numerical format. The simplest way to achieve this is by using a unary plus operator +.

const
    game = { team1: 'Bayern Munich', team2: 'Borrussia Dortmund', players: [['Neuer', 'Pavard', 'Martinez', 'Alaba', 'Davies', 'Kimmich', 'Goretzka', 'Coman', 'Muller', 'Gnarby', 'Lewandowski'], ['Burki', 'Schulz', 'Hummels', 'Akanji', 'Hakimi', 'Weigl', 'Witsel', 'Hazard', 'Brandt', 'Sancho', 'Gotze']], score: '4:0', scored: ['Lewandowski', 'Gnarby', 'Lewandowski', 'Hummels'], date: 'Nov 9th, 2037', odds: { team1: 1.33, x: 3.25, team2: 6.5 } };


for (const [i, v] of Object.entries(game.scored)) {
    console.log(`Goal: ${+i + 1} ${v}`);
}

Answer №2

game.scored.entries() generates an iterator object where the indexes are numerical values. By adding 1 to the i, you can achieve the desired outcome.

Object.entries(game.scored) returns the key as a string. So, when you perform i + 1, it concatenates instead of performing addition because i is in string format. This results in converting 1 into a string and then combining it with the value of i.

To ensure accurate results, it is recommended to convert i to a number before adding 1 to it.

There are several methods to convert a string to a number:

  • Using the unary operator +

    for (const [i, v] of Object.entries(game.scored)) 
    {
      console.log(`Goal: ${(+i) + 1} ${v}`);
    }
    
  • Utilizing the parseInt() function

    for (const [i, v] of Object.entries(game.scored)) 
    {
      console.log(`Goal: ${parseInt(i) + 1} ${v}`);
    }
    
  • Applying the Number() constructor

    for (const [i, v] of Object.entries(game.scored)) 
    {
      console.log(`Goal: ${Number(i) + 1} ${v}`);
    }
    

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unleashing the power of DOM events through jQuery observables

I'm a bit confused at the moment. I'm working with an Angular project using a Bootstrap theme. Someone has implemented tab functionality using Bootstrap, but there's an issue - it's all written in JavaScript. This means that events such ...

Tips for adjusting the height of a div using the slideToggle function for expanding and collapsing content

Is there a way to modify my code in order to adjust the height of a <div> using slideToggle()? The current implementation works almost correctly, with one minor issue. When I click on one "read_more" and then click on another, it does not behave as e ...

Dynamic Wave Effects with jQuery

I'm interested in developing an interactive animation where waves emanate from a central point and trigger similar waves of varying sizes at outer nodes in a circular pattern. After researching, I came across a few libraries: https://github.com/mbos ...

The purpose of raising exceptions

Why do we throw exceptions in programming? I came across this example: static List<Integer> list(int [] a) { if (a == null) throw new NullPointerException(); //... But if you don't throw the NullPointerException, won't ...

Proper method for incorporating loading and error messages with the help of useContext and react hooks

Currently, I have a context.js file that makes an ajax call and stores the data in an array to be shared across components. While adding some 'loading ...' text during the loading process using axios, I feel there might be a better way to handle ...

Obtaining the HREF of the selected anchor text in TinyMCE

I can retrieve the selected text in TinyMCE using var selection = parent.tinyMCE.activeEditor.selection.getContent(); but how can I access the href of text that has already been linked? For example, if the text was hyperlinked to http://www.youtube.com, ...

Unable to access the attributes of the mongoose model

I'm experiencing an issue with my mongoose model.find code below Displayed here is my node.js code that utilizes mongoose to interact with MongoDB. However, upon running it, I encounter the following error message: Starting... (node:7863) Unhandl ...

Issue arises when component is mistakenly displayed in the header upon deployment on Vercel platform

When deploying my NextJS app to Vercel, I encounter an issue where state-based modals that should be hidden are displaying. Additionally, the modals are rendering in the header instead of center-screen as expected. Surprisingly, these problems do not occur ...

Extract the data that was returned from the AJAX post function

I am looking to create a condition that is dependent on the data received from an ajax post outside of the post function function post(){ $.post('page.php',$('#form').serialize(), function(data) { if(data !== 'good'){a ...

Maintaining the footer and bottom section of the webpage

I am facing an issue with the footer on my website . I want the footer to always stay at the bottom of the page, even when I dynamically inject HTML code using JavaScript. The footer displays correctly on the main page , but it does not work as intended on ...

Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it : <div class="map"> <div class="map-page" tabindex="0" @keyup.arrow-keys="show" ref="mapPage"> <template v-for="mapRow in mapMatrix"> < ...

`methods that exhibit peculiar behaviors`

My routes are set up with the get method. app.get("/info/teachers", controller1); app.get("/info/teachers/:teacherid", controller2); app.get("/info/students", controller3); app.get("/info/students/:studentid", contr ...

Search a database for a specific set of ObjectID using Mongoose

I'm currently developing an API using node.js, express, and mongoose. As I am still new to mongosse, I have been exploring different approaches to achieve what I need. In my database, I have two collections: users and expenses. Here's an exampl ...

Tips for altering symbol hues in Angular 4 pipelines

Can the color of the Angular 4 pipes symbol be customized? I am looking to change the dollar symbol to a lighter color, for instance. Link to Image The price shown is formatted using the currency pipe: currency:'USD':'symbol-narrow': ...

Connecting an ActionLink to a jQuery button in an MVC framework

Is there a way to link an ActionLink to a jQuery button on an ASP.NET MVC page? <button id="Button1">Click</button> <%: Html.ActionLink("About", "About", "Home")%> <script language="javascript" type="text/javascript"> $(fun ...

Steps for storing div content (image) on server

Currently in the process of developing a web application that allows users to crop images. The goal is for users to have the ability to email the URL so others can view the cropped image, ensuring that the URL remains active indefinitely by storing every c ...

Is it possible to apply CSS animations to manipulate HTML attributes?

I'm exploring how to animate an HTML element's attribute using CSS and looking for guidance. While I am aware that you can retrieve an attribute using the attr() CSS function, I am unsure about how to modify it. Specifically, I am attempting to ...

The functionality of jQuery mouseenter and mouseleave events seems to be malfunctioning when applied to newly injected DOM elements

I encountered an issue with my code. It functions properly, but when I introduce new elements into the dom, it fails to show or hide them. jQuery("div.cat-icon").on({ mouseenter: function () { jQuery(this).find('.catselect').show( ...

Fuzzy background when you scroll

My container has an image that blurs when you scroll down the page by 50 pixels. I feel like I've seen this effect somewhere before, but I can't quite recall where. I want the text to remain unaffected and not turn blue. Here is the HTML: <d ...

Pass the JavaScript variable to the Laravel controller for updating VueJS

Trying to send data from my modal to a controller to update data, but I'm not sure how to declare my variable and how to send this variable... Here is my current code: Vue.js <script> export default { data() { return { ...