Adding an object to an array using the Array.push() method deposits an array

Currently, I am extracting the days of absence of my colleague from excel files and storing them in a MongoDB database using Mongoose and Express.js.

The process of reading the data is smooth; however, when trying to update the data in the database, an unexpected behavior occurs. When inserting an Object into an array using Array.push(), it results in an Array of Objects containing a single object inside the outer array.

The function provided below retrieves raw data from the excel files and attempts to save it in the database. Please excuse the messy code, as I was only prototyping ;-)

function getDaysOff( data, callback )
{
    Member.find({}, function( err, docs ) {
        if ( err )
        {
            console.error( err );
            return [];
        }
        console.log( "found " + docs.length + " team members" );
        docs.forEach( function( element ) {
            // reset all arrays before continuing
            element.days_of_absence = [];
        } );
        data.forEach( function( element ) {
            for ( let i = 0; i < element.length; ++i )
            {
                var member = element[i];
                for ( let j = 0; j < docs.length; ++j )
                {   
                    if ( member.name.match( new RegExp( docs[j].name, 'g' ) ) )
                    {
                        console.log( member.name + " is " + docs[j].name );
                        for ( let k = 0;  k < member.absent.length; ++k )
                        {
                            docs[j].days_of_absence.push( member.absent[k] );
                            console.log( JSON.stringify( member.absent[k] ) );
                        }
                        console.log( JSON.stringify( docs[j].days_of_absence ) );
                        break;
                    }
                }
            }
        } );
        docs.forEach( function( element ) {
            element.save();
        } );
        callback( docs );
    });
}

Here is the schema for the Member:

var mongoose = require('mongoose')  
var MemberSchema = new mongoose.Schema(
    {
            _id: {
                        type: 'ObjectId'
                    },
            name: {
                        type: 'String'
                    },
            prename: {
                        type: 'String'
                    },
            days_of_absence: {
                        type: 'Array'
                    }
    }
);
module.exports =  mongoose.model('Member', MemberSchema, 'members');

When printing days_of_absence, the output looks like this:

[
  [ { "date": "2018-01-28T23:00:00.000Z", "reason": "P" } ],
  [ { "date": "2018-01-29T23:00:00.000Z", "reason": "P" } ],
  ...
  [ { "date": "2018-09-27T22:00:00.000Z", "reason": "P" } ]
]

The issue arises with the additional arrays around the objects. I have confirmed that member.absent[k] contains the desired objects within the inner array. However, I cannot figure out where the extra arrays are coming from. What could be causing this? Any insights or solutions would be much appreciated.

UPDATE

After testing, it has been verified that member.absent[k] is not an array. The loop displays the intended output console.log( member.absent[k] ):

{"date":"2018-09-02T22:00:00.000Z","reason":"P"}

Answer №1

Upon examination, it appears that you are dealing with an array labeled member.absent[k]. To simplify and obtain a single object, you can utilize the spread operator.

docs[j].days_of_absence.push(...member.absent[k]);

If there is uncertainty about whether the value is always an array, you have the option to create one and then spread it accordingly.

docs[j].days_of_absence.push(...(
    Array.isArray(member.absent[k])
        ? member.absent[k]
        : [member.absent[k]]
));

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

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Utilizing a switch statement for form validation

Currently, I am in the process of creating a form validation that involves two conditions for validation. I'm considering using a combination of switch case and if else statements. Would this be an appropriate approach or is it generally discouraged? ...

Ways to retrieve a specific value in an array of objects

When working with the p5 javascript library, there is a convenient built-in function called {key} that captures the key you press. For instance, using text(${key},200,200) will display the key pressed at position 200, 200 on the canvas. If I were to stor ...

Determine if a file input is linked in React.js Material UI

Currently, I am working with a Material UI <TextField /> component that has a type=file prop to allow file attachments. My goal is to trigger an event when a file is attached to this TextField. However, my search results only provided JQuery soluti ...

Converting every item's values into keys

Currently, my goal is to export all object values as keys specifically for a tree-shakable import system in a plugin I'm currently developing. The approach involves dynamically importing modules from various directories and subfolders, consolidating t ...

Tips on finding the ID of a textbox using the cursor's position

In the container, there are several textboxes. When a button is clicked, I want to insert some text at the cursor position in one of the textboxes. I have managed to insert text into a specific textbox using its ID, but I am facing difficulty in identifyin ...

Dynamically insert a new row into an HTML table using AJAX and refresh the table with .load method

I am facing an issue with my HTML table that loads data dynamically through a PHP snippet containing SQL queries. There is a Select option and a button on the table to add a new row, which triggers an AJAX procedure to send the data to PHP for insertion in ...

Unlock the potential of Stripe's confirmCardSetup method when working with multiple elements in Laravel Cashier integrated with a Vue application. Master

Is it possible to send inputs separately from Stripe using the confirmCardSetup method, even though the documentation only mentions one cardElement element? https://stripe.com/docs/js/setup_intents/confirm_card_setup -> check the official documentation ...

What is the best way to retrieve the value of an UL LI element using jQuery

I'm struggling to retrieve the value of a ul li listbox in a function, and I can't seem to figure out how. Here is my code: <ul class="dropdown-menu" id="newloc"> <?php $res_add = DB::table('res_br')-& ...

Combine two scope arrays in AngularJS

Is there a way to merge two arrays of scope in AngularJS within my controller so that I can display them in a single table? The merging would be based on a common field present in both arrays, similar to an SQL join operation where data from both tables ...

Combining a 3D array into a 2D array with the addition of HTML tags around each value using JavaScript

3D array // Array var x = { "letter": [ "a", "b", "c", "d", "e", "f", "g", "h", "i" ], "line": [ { "data": [ 306, 830, 377, 651, 547, 369, 300, 148, 494 ] }, { "data": [ 88, 339, 298, 87, 96, 108, 93, 182, 64 ] }, { "data": [ 3157, 2943, ...

What are the best practices for managing data input effectively?

I am facing a challenge with input validation. I need to restrict the input to only accept strings of numbers ([0-9]) for the entity input field. If anything else is entered, I want to prevent it from overwriting the value and displaying incorrect input. I ...

How do I retrieve and display all the locally stored variables in Angular 2/JavaScript and calculate the total number of keys present in the localStorage?

Currently, I'm developing a project in Angular2 that involves the storage of user-added items to a shopping cart. To accomplish this, I have opted to utilize local storage to temporarily save the items. Each category (such as shoes, clothes, etc.) is ...

Regular expression for matching zero's following a decimal

I'm currently working on a regex method to validate decimals that only allow 2 numbers after the decimal point. For example, it should return true for 1.00 and false for 1.000, which it currently does. However, I also want it to return false for value ...

Increasing the size of text in CSS with the use of ":hover" and then causing it to return to its original smaller size

Allow me to explain my goal here. I have text displayed on my website that I would like to enlarge when the user hovers over it and then shrink back down when they move their cursor away. The issue I'm facing is that after enlarging the text using t ...

Is it possible to utilize personalized functionalities in the main.js file of the Firefox Addon SDK?

Why am I encountering difficulties accessing custom functions with the Firefox Addon SDK? In the code snippet provided below, whenever I click on context menu Sub Item 1, it does not work as intended; It is trying to access the custom function verifyTest( ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Data is not being successfully passed through Ajax

Having some issues with passing data through ajax. I've used this method multiple times before without any problems, but now it's not returning anything. Here is the javascript code: $('#contactformbtn').click(function(){ var full ...

Implementing a gradient effect on a specific image element within an HTML canvas with the help of jQuery

Currently, I'm working on an HTML canvas project where users can drop images onto the canvas. I am looking to implement a linear gradient effect specifically on the selected portion of the image. My goal is to allow users to use their mouse to select ...

Guide to Triggering a Page View Event in Google Tag Manager with Angular

Previously, I manually fired the Page View Event using JavaScript from app.component.ts while directly accessing Google Analytics: declare var gtag: Function; ... constructor(private router: Router) { const navEndEvents = this.router.events.pipe( fil ...