The connection between two arrays remains intact even after using the .push() method in JavaScript or Vue.js

I need help setting up two arrays containing dates. The first array should have the dates in string format, while the second array should contain the same dates but as date objects.

methods: {
    test() {
        let employments = [
            { begin: '01.01.2000', end: '01.01.2010' },
            { begin: '01.01.3000', end: '01.01.3010' },
            { begin: '01.01.4000', end: '01.01.4010' }
        ];
        let items = [];
        for(let i = 0; i <  employments.length; i++) {
            items.push(employments[i]);
        }
        for(let i = 0; i < items.length; i++ ) {
            // splitting it up for the correct format
            let begin = items[i].begin.split('.').reverse().join('-');
            let end = items[i].end.split('.').reverse().join('-');
            items[i].begin = new Date(begin);
            items[i].end = new Date(end);
        }
        console.log('items:');
        console.log(items);
        console.log('this.employments:');
        console.log(employments);
    }
}

The intended outcome was to generate two separate outputs - one with strings and the other with date objects. However, I ended up with two arrays containing only date objects. This is not what I expected and I'm unsure why this occurred.

I also attempted to assign employments directly to items like "let items = employments;" instead of using the push method, but this approach did not yield the desired result either.

Any assistance is greatly appreciated.

Answer №1

To create a new array with copies of objects, you should use the push() method. Since your object is shallow, you can utilize the spread operator to easily duplicate it.

for(let i = 0; i < employments.length; i++) {
     items.push({...employments[i]});
}

Alternatively, you can achieve the same using:

const items = employments.map(x => ({...x}))

Avoid creating another array and then pushing into it. Instead, utilize map() on the original employments array and modify the properties directly. It's also beneficial to create a separate function for generating Date objects.

methods: {
    test() {
        let employments = [
            { begin: '01.01.2000', end: '01.01.2010' },
            { begin: '01.01.3000', end: '01.01.3010' },
            { begin: '01.01.4000', end: '01.01.4010' }
        ];
        const format = str => new Date(str.split('.').reverse().join('-'));

        let items = employments.map(({end,start}) => 
                          ({
                              end: format(end),
                              start:format(start)
                          })
                    )

    }
}

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

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

Get the PDF document via FTP by utilizing an XMLHttpRequest and a generic handler

Attempting to download a PDF file from an FTP server using a JQuery Ajax request. The reference used was found at . Below is the Jquery ajax call being made: $.ajax({ xhr: function () { var xhr = new window.XMLHtt ...

What mistakes did I make in setting up passport-jwt?

I integrated passport-jwt into my MEVN-stack application successfully for logging in. However, I encountered a 401 Unauthorized error in the console when trying to redirect to the home page after login. Even though I passed the token as the value of the Au ...

Remembering previous scroll position with jScroll upon revisiting page

I'm implementing infinite scrolling of products on our site using jQuery jScroll. Can anyone guide me on how to save the scroll position when the user returns to the homepage? Appreciate any assistance! ...

Unlocking the Power of Global Props in AlpineJS: A Step-by-Step Guide

I'm currently exploring AlpineJS after having some experience with React and basic knowledge of Vue. One thing that has puzzled me about AlpineJS is how to update a state value from within a function, similar to how it's done in React. Let' ...

What are some creative ways to customize and animate the cursor or caret within an input field?

Just to clarify, I am working with React and Material-UI. I have a task at hand where I need to modify the appearance of the caret within an input element by adding an animation to it. I have managed to change its color using caret-color and set a default ...

Filtering data in a dataframe using an array of specified values

I am dealing with an array named df and a dataframe called data. The array contains unique IDs, for example: df=array([10,11,12]). The dataframe has 3 columns: data, id, value. My goal is to filter the dataframe so that it only includes IDs specified in ...

Is there a way to set up a vue-good-table to automatically switch to the next page every 5 seconds?

I came across an example of a vue-good-table in one of their tutorials, but I have a unique requirement. I want the table to automatically move to the next page every 5 seconds, and when it reaches the end, restart back at page 1. How can this be achieved? ...

What could be the reason for the modal-side modal-top-right class not functioning properly in Bootstrap modals

Here is the code snippet: <div class="modal fade right" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-side modal-bottom-right"> <div class="modal-content"&g ...

The edges of the cubemap in THREE.js appear murky

I am attempting to create a black skybox with white dots (stars) in three.js. However, due to the perspective effect, the dots appear darker in the corners where they are further away (as they get smaller and dimmer). Is there a way to make the appearance ...

Implementing database queries using an API in Nuxt/Vue: A step-by-step guide

Recently, I delved into Vue/Nuxt and started playing around with API integration. My goal is to transfer the logic from my NuxtServerInit function to an API. nuxtServerInit(vuexContext, context) { return context.app.$axios .$get(process.env.baseUrl ...

Exporting Javascript functions is not possible

Programming in TypeScript import { Component, OnInit } from '@angular/core'; import {loadCalendar} from '../../../../scripts/artist/artist-home'; import {activate_searchBar} from '../../../../scripts/search_bar_activate'; @C ...

Adding a dynamic form to each row in a table: A step-by-step guide

https://i.sstatic.net/HctnU.jpg Hey there! I'm facing a challenge with dynamically generated rows in a form. I want to send only the inputs from the selected row when a checkbox is clicked. Can you help me figure this out? I tried using let rowForm ...

Steps to successfully retrieve an image using JavaScript on the client side while circumventing any CORS errors

I have a React application where I am displaying an image (an SVG) and I want the user to be able to download it by clicking on a button. The image is stored in Firebase Storage. However, I am encountering an issue with CORS error: Access to fetch at &ap ...

Utilizing JavaScript for loops to extract the final element from an array

I am facing an issue with the second loop within a function that goes through a JSON file. The problem is that it only returns the last item in the array. I need to figure out how to fix this because the chart object should be created on each iteration, ...

Having trouble loading select fields using AJAX within Wordpress? Update and find a solution!

UPDATE: I am struggling to iterate through the response object and populate a select field using my ajax function. Although I have tried using a for loop instead of each(), the select field gets populated with "undefined". Any suggestions on how to resolve ...

Using Express.js to Serve Static Content on a Dynamic Route

I am working with the app.js code below; app.use(express.static(__dirname + "/public")); app.use("/example", express.static(__dirname + "/public")); app.engine("html", require("ejs").renderFile); app.get("/", (req, res) => res.render("index.ejs")); a ...

Update vue-table-2 to activate search filter upon button click, rather than keystrokes

exploring the capabilities of https://github.com/matfish2/vue-tables-2 using Vue.js version 2.6.11 Hey there! I'm a newbie developer delving into Vue.js after working in the React world. I'm aiming to modify the filter/search functionality to tr ...

Tips for creating various instances of a single type within mock data

In my Schema.js, I have a simple schema and server setup: const typeDefs = gql` type Query { people: [Person!]! } type Person { name: String! age: Int! job: String } `; And here is my server configuration: const mocks = { Person ...

Having trouble integrating an HTML template using JavaScript

I am currently attempting to integrate the HTML code of my website using data-prototype: <div id="accordion" data-prototype=' <div class="card-body"> <textarea id="solution_answers___name___content" name=& ...