JavaScript array push is not functioning as expected

Having trouble getting my push function to work properly..

Here is my code snippet:

   var result = {};


dpd.timesheetsdone.get(function (timesheets, err) {
  if(err) return console.log(err);

  timesheets.forEach(function(entry, index) {

   result[entry.timesheets[0].week] = [];
   result[entry.timesheets[0].week].push(entry);
     //here is where I'm trying to push
  }
   );
    setResult(result);

});

When the code runs, it doesn't actually push the entry, it just assigns it and sets result to one item. It's not pushing as intended.

What could be causing this issue?

An example of the timesheets can be found here.

Answer №1

The issue lies in this section:

result[entry.timesheets[0].week] = [];

Any previous data stored there will be overwritten; hence, only the latest information for that week is visible.

To prevent overwriting existing data, you should check if the assignment has been done already:

if (!result[entry.timesheets[0].week]) {
    result[entry.timesheets[0].week] = [];
}

For example:

var result = {};

dpd.timesheetsdone.get(function(timesheets, err) {
    if (err) return console.log(err);

    timesheets.forEach(function(entry, index) {

        if (!result[entry.timesheets[0].week]) {
            result[entry.timesheets[0].week] = [];
        }
        result[entry.timesheets[0].week].push(entry);
    });
    setResult(result);

});

Alternatively, to minimize object lookups:

var result = {};

dpd.timesheetsdone.get(function(timesheets, err) {
    if (err) return console.log(err);

    timesheets.forEach(function(entry, index) {
        var week = entry.timesheets[0].week;
        var weekArray = result[week];
        if (!weekArray) {
            weekArray = result[week] = [];
        }
        weekArray.push(entry);
    });
    setResult(result);

});

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

Creating a key-value pair array upon checking a checkbox with jQuery

Every time I check a checkbox, two key-value pairs are generated, such as: Object {id: "101", name: "example"} These pairs are generated for each checked checkbox, and I want to create an array with multiple checkbox values that look like this: [{id:" ...

Utilize text-to-speech technology to convert the output results into

Looking for a way to live stream a text to speech message triggered by a button press on your website? Unsure how to accomplish this with Node.js and generate the file after the button press? Let's explore some solutions together. ...

JavaScript failing to accurately measure the length

Currently experiencing a Javascript issue where the length of an element is not displayed correctly when using .length, even though it shows up in Chrome console. Here is what it looks like in Chrome console <html xmlns="http://www.w3.o ...

Implementing dynamic row transitions with Vue.js on tables

I'm struggling to implement a transition effect on an HTML table row using Vue.js. Here is the complete example: new Vue({ el: '#data', data: { items: [ { data: 'd1', more: false ...

How to utilize Val() function for assigning a value to a hidden field within an ASP.NET web form

I am attempting to utilize val() in order to alter the value of a hidden field within asp.net. Here is my jQuery code: $("#blue").val("Green"); ASP: <asp:HiddenField ID="blue" runat="server" clientidmode="static"/> The desired outcome is: <a ...

The dropdown feature stores and displays only the initial value

After resolving my previous question (link), I am now facing a new issue where the value of the name field is only reflecting the first item in the dropdown list. Let me explain further. I have two dropdown menus, where selecting an option in one (A) dyna ...

Discover the array of results by implementing a while loop in JavaScript

My goal is to create a list of outputs that are not evenly divisible by numbers smaller than the input value. For example, if the input value is 10, the list should be 10, 9, 8, 7, 6, 4, 3, 1. I have written some code in JavaScript for this purpose, but ...

Creating a function to determine if at least one checkbox has been selected

<div class="form-group"> <div class="row" style="margin-top: 10px;"> <div class="weekDays-selector checkbox-inline" ng-repeat="day in vm.days" ng-if="vm.pen.feeding_frequency.name == 'Custom'"> <input type="checkb ...

"Revitalize your React JS project with a rerender

Trying to refresh a list with filtered values... Already displayed all values but now want to show them again with a dropdown menu. Data is sourced locally from a JSON file. [ { "brand": "Toyota", "model": "Corona", "cylinders": 4, "horsepower": 96, "orig ...

WebAPI provides a similar functionality to an array in JavaScript through the use of IQueryable

I have a WebAPI method that returns an IQueryable of a 'complex' object in the following format: [Route("api/INV_API/deptSelect")] public IQueryable<DEPTNAME_DESCR> GetDistinctDeptSelect([FromUri] string q) { if (q != null) ...

Inspect the key within a complex hierarchy of nested objects in an array

I am working with an array of nested objects and need to extract the value of a specific key property. Currently, I am using a for loop and checking for the existence of children property, but I feel there might be a more optimal way to accomplish this tas ...

Tips for displaying the sum of a grouped field in the balloonText using Amchart

I recently started working with Amcharts and I am seeking advice on what I may be doing incorrectly. Below is the snippet of my JavaScript code: var chartData1 = []; generateChartData(); function generateChartData() { var month = new Array( ...

Problem with selecting odd and even div elements

I have a div populated with a list of rows, and I want to alternate the row colors. To achieve this, I am using the following code: $('#PlatformErrorsTableData').html(table1Html); $('#PlatformErrorsTableData div:nth-child(even)').css(" ...

Once the data in the React context has been updated, the next step is to trigger a re-render of the

In my React application, I have implemented a system where certain components will display based on whether the user is logged in or not. To ensure this state is shared throughout the entire application, I created a context file called AuthProvider: import ...

When the section comes into view on the screen, the CSS animation will play only one time

While browsing through , I found some fantastic animations that inspired me. The animations at the header seem to be standard CSS animations with delays. However, as you scroll down and other sections become visible, the animations reappear only once. Can ...

Tips for restricting the size of inserted content in a contentEditable paragraph

I am in need of a one-line editable paragraph that can contain text without overflowing its size. Currently, I am using CSS to hide the overflow and prevent multiple lines by not displaying the children of the paragraph. However, what I really want is fo ...

Having trouble loading JavaScript in my Django and React Project using Vite.js - need some help!

After creating a project with React as the frontend and Django as the backend, I organized them into separate folders: backend and frontends (please disregard the deliberate spelling mistake). To build the React project, I utilized vite.js and then genera ...

Guide on Developing a JavaScript Library

After creating several JavaScript functions, I noticed that I tend to use them across multiple projects. This prompted me to take things a step further and develop a small JavaScript Library specifically for my coding needs. Similar to popular libraries l ...

Encountering the error message "TypeError: Cannot read property 'filename' of undefined" while attempting to run the `npm start` command

I came across a lengthy but insightful post that explains how to set up a web application using the following technology stack: es 6 node + express handlebars react + react router webpack + babel You can find the sample code here. I have been followi ...

Angular JS Directive is a powerful feature that allows developers

There are three HTML screens available. Screen1.html: <button id="screenbtn"></button> Screen2.html: <div id="sctmpl"> <label>Label for screen two</label> </div> Screen3.html: <div id="sctmpl1"> <l ...