The loop outcome is not determined

Storing function arguments in a specific format

["2015-07-05 00:30", 59]
...
["2015-07-05 01:00", 62]
function generateCSV(timeAndValue) {
    object = {}
    var zero = 0;
    for(i = 0; i < timeAndValue.length; i++){
        var value = timeAndValue[i]
        var days = moment(value[0]).format('YYYY-MM-DD');
        obj[days] += value[1] + ', '
    }
}

It assigns the days and total values spent on each day while looping. 2015-07-05:

"2015-07-05: "undefined59, 62, 65...

2015-07-06: "undefined61, 61, 60..."

Each parameter starting with "undefined". How can I prevent this?

Answer №1

Revise

obj[days] += value[1] + ', '

Replace it with

if (obj[days]===undefined) obj[days] = ''; 
obj[days] += value[1] + ', '

This change prevents adding a string to undefined.

Instead of appending ", " after each value, consider creating an array within your loop:

if (obj[days]===undefined) obj[days] = []; 
obj[days].push(value[1])

Later, use join to avoid the trailing comma and defer string manipulation until rendering.

Double-check variable declarations: object might be fine if defined in an outer scope, but beware of undeclared variables like i, which could cause issues if used elsewhere in your codebase.

Edit: A typo was pointed out by James - it should either be "object" or "obj".

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

Problems with Angular UI Router: Functions not functioning properly within the template

Currently, I am delving into the realm of Angular UI Router in order to effectively manage different sections of my application. If you'd like, check out this plunkr (http://plnkr.co/edit/KH7lgNOG7iCAEDS2D3C1?p=preview) Here are some issues that I&a ...

There was a problem with the ES Module requirement while trying to use retry-axios, resulting in the following error: [

const rax = require('retry-axios'); Error [ERR_REQUIRE_ESM]: encountered an issue with require() for ES Module While attempting to set up a retry mechanism using retry-axios, I ran into the Error [ERR_REQUIRE_ESM]: require() of ES Module error. ...

Issue encountered while trying to set a property in ECMAScript 6

I am attempting to create a class in ecmascript 6. Below is the code: class Machine { constructor (){ this._context = null; } get context (){ return this._context; } set context (context){ this._context = context; } ...

What is the process for loading my new fonts into an HTML document?

I am trying to incorporate two specific fonts, bigsmalls-bold and lft-etica-web, into my CSS and HTML code. Unfortunately, I have been unable to find a way to download these fonts directly. The only information I found was a JavaScript code snippet on I a ...

I am experiencing issues with my three.js Raycaster functionality. Does anyone know how to troubleshoot and resolve this problem

Once I set up my new project using three.js, I followed the instructions in the three.js documentation to add a Raycaster and connect it to a cube. The goal was to make the cube follow the cursor's position, but unfortunately, the cube ended up moving ...

The Controller is failing to pass JSON Data to the AJAX Call

When trying to access JSON data in the Controller, it is not being retrieved in the Success function and instead showing an error message "Failed to load resource: the server responded with a status of 406 (Not Acceptable)" or executing the Error function. ...

ReactJS component disappearing behind the Navbar

When using my React app, I have a navigation bar at the top. The Navbar component is called in App.js, and the code snippet below shows how it is implemented. export default function App() { return ( <Router> <Fragment> ...

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

What is the best way to trigger two functions simultaneously using an onClick event in NextJS?

I have defined two constants in my NextJs app, "toggleMenu" and "changeLanguage". When the language changer inside the menu is clicked, I want it to trigger both of these functions. However, I tried implementing this code but it doesn't seem to work ...

Visualizing Data with d3.js Radar Charts Featuring Image Labels

After following a tutorial on creating a d3.js radar chart from http://bl.ocks.org/nbremer/21746a9668ffdf6d8242, I attempted to customize it by adding images to the labels. However, I encountered an issue with aligning the images properly. You can view my ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

Tips for accessing the data from an object's num property using the name property as a selector

I am attempting to locate the value of the num property within this object by using the name property to identify the correct object from the hashtagsl array; thus, obtaining the correct num value. I need to accomplish this task with only the information o ...

Using a JSON file as a variable in JavaScript

Hello there everyone! I am looking to create a multilingual landing page. The idea is to have a language selection dropdown, and when a language is chosen, JavaScript will replace the text with the corresponding translation from a JSON file. However, I a ...

What's the reason for seeing "1:powershell" in the terminal when using react.js?

Can anyone explain why the terminal shows "1:powershell" in react.js? https://i.sstatic.net/1LyHe.png https://i.sstatic.net/5K95B.png ...

A guide on protruding a specific triangle within a mesh using three.js

Description: In my three.js project, I have implemented a selection tool that allows users to click and drag over the mesh to color the triangles red. Now, I am looking to create a function that will examine the mesh.geometry.attributes and extrude any tr ...

The panel widens unexpectedly despite the initial coding plan

I am in the process of creating a panel with a specific area where users can resize it by dragging their mouse cursor. However, instead of moving smoothly, the panel unexpectedly jumps in size before becoming resizable. Upon inspecting the element, I noti ...

What is the best way to position a tooltip near an element for optimal visibility?

One div is located on the page as follows: <div id="tip"> Text for tip goes here... </div> And another one can be found below: <div class="element"> Text for element goes here... </div> There is also a piece of JavaScript ...

Transforming the appearance of the menu element in Vue using transitions

In my Vue app, I have this SCSS code that I'm using to create a smooth transition effect from the left for a menu when the isVisible property is set to true. However, I am encountering an issue where the transition defined does not apply and the menu ...

Show the full-size image in a web browser with its true dimensions

Currently, I am faced with the challenge of showcasing an image on a web browser with specific dimensions - 2200px width and 1600px height. The issue is that the image is being displayed by zooming in, with only one zoom option available as default. My g ...

Error: The validation process for schema[parameter] cannot be completed as the function validateAsync is not

While attempting to develop an API using express, I encountered the error mentioned above. Despite referring to various GitHub resources with solutions to similar issues, none of them seem to resolve my problem. Below is the code snippet: API: http://loca ...