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

VueJS refreshes components while preserving previous data

As a newcomer to VueJs, I am currently working with a Practice component that includes an ExerciseMC component. The parent component retrieves a question object (with a text property) from the backend through a request and passes it as a prop to the Exerci ...

The Vue-cli Webpack template is experiencing issues with correctly serving static fonts

Within my configuration file index.js, specifically in the build section, I have specified: assetsSubDirectory: 'static', assetsPublicPath: '/path/to/subdirectory/', This means that the static fonts sourced from a theme template impor ...

Unexpected shift in margin appearance: Vuetify acting strangely?

I'm currently working on a project in a new location and I've noticed some differences in the margins compared to my previous work environment. Despite having the same package.json, the only change seemed to be due to a new npm install. For insta ...

Error encountered: Cordova plugins return undefined values when testing on an actual device

I am currently utilizing Phonegap in conjunction with ngCordova and AngularJS. The aim is to leverage the capabilities of the plugin (PhoneGap-Image-Resizer) to facilitate media saving on the device. However, I encountered an issue where the plugin throws ...

Instructions for including dependencies from a globally installed npm package into a local package

I've noticed that although I have installed a few npm packages globally, none of them are showing up in any of my package.json files. What is the recommended npm command to automatically add these dependencies to all of my package.json files? ...

Placing a component within a div element using Vue

I recently integrated a Vue module to make objects draggable and resizable on my project. In my design, I envisioned creating movable and sizable boxes that contain dropdown menus, input fields, and radio buttons. As a starting point, I have included a sim ...

Dealing with redirect issues in a React-Material menu: A guide to troubleshooting and

When working with my menu, I face a variety of issues. First and foremost, within the initial RETURN section, there is a TREEITEM with a LISTITEM and a LISTITETEXT. I have included an OnClick event in the LISTITETEXT so that if the menu's id matches ...

Setting headers in Node.js after they have already been sent to the client is not allowed

I'm currently enrolled in a node.js course on Udemy which seems to be outdated. I've encountered some errors that I'm struggling to resolve. Here's what I've tried so far: using next(); adding return res inside all if statements ...

When applying the OWASP ESAPI encodeForHTMLAttribute method, I noticed that symbols are being rendered as their corresponding HTML entity numbers instead of the actual symbols

I recently started exploring OWASP ESAPI for preventing XSS and integrating the JavaScript version into my application. As per Rule #2 in the XSS prevention cheat sheet, it is recommended to "Attribute Escape" before inserting untrusted data into attribut ...

Passport Node: Issue with Password Comparison results in an undefined function error, causing return done(null, user) to fail

I have reviewed all the relevant inquiries and responses but I am still unable to resolve this issue. Please see the code provided below and assist me in understanding why the terminal is displaying 'undefined is not a function'. Here is an overv ...

Iterating through an array with a .forEach loop and referencing the variable name

Currently, I am working on a project using JS/React and dealing with nested arrays in an array. The structure of my data looks like this: const ezra = ["Patriots", "Bears", "Vikings", "Titans", "Jets", "Bengals"] const adam = ["Chiefs", "Cowboys", "Packer ...

In node.js, what is the syntax for invoking a function within a struct from that same function?

Here is a brief overview of my code: exports.entity = { name: "Foo", //Etc... start: function () { this.attack(); }, attack: function () { setTimeout(attack, 1000); //Doesn't work ...

What sets asyncData apart from methods in Nuxt.js?

I am currently utilizing asyncData to fetch data from an API, however it is restricted to pages and cannot be used in components. On the other hand, methods can be used in both pages and components. As these two methods function similarly, I am consider ...

Experiencing difficulties when attempting to send a cookie to the server

Why is the vue+axios frontend not sending cookies to my php server in the request header? I am currently in the process of migrating an old project to a new server. After making some optimizations to the project architecture, everything worked perfectly f ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

What is the best way to show an SVG icon in React without having to make an HTTP request for the file?

A special requirement for a react application is to display icons in certain parts of the application while offline. The use of inline svg is particularly fitting for this purpose. import React from 'react'; // Utilizing inline svg to showcase i ...

Creating dynamic web pages with jQuery is a simple and effective

I am currently using jQuery to create HTML elements with specific classes and then append them together. However, the code I have written is not adding the generated HTML to the container as expected. There are no errors being produced but the HTML is not ...

What is the syntax for creating ES6 arrow functions in TypeScript?

Without a doubt, TypeScript is the way to go for JavaScript projects. Its advantages are numerous, but one of the standout features is typed variables. Arrow functions, like the one below, are also fantastic: const arFunc = ({ n, m }) => console.log(`$ ...

Expanding/Combining entities

I'm facing an issue while trying to Extend/Push/Merge an object using AngularJS. The problem arises when I attempt to extend the object, as it adds a new object with an Index of 0 and subsequent additions also receive the same index of 0. //Original ...

Unable to activate Vue 13 keyCode in a text field using jQuery with Laravel Dusk Testing

I've been grappling with this issue for a few days now. I'm trying to create a Laravel Dusk test that incorporates the Vue.js framework. There's a method that should be triggered when the user hits the ENTER key. I recently discovered that ...