One array still refers to a second array after .push()-method (JS/vue.js)

Viewed 271

I want to have two arrays filled with dates. The first one should have those dates in string-format and the second should be the same dates 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);
    }
}

I expected to have two different outputs. One with strings in it and the other one with date objects. What I got instead were two arrays with date objects. And I just don't get why.

I also tried directly giving employments to items (like "let items = employments;" ) instead of doing the push-method, but this didn't work either.

Thanks in advance

1 Answers

You are need to push() a copy of object. Your object is shallow object so you can use spread operator to create a copy.

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

Or simply you can do

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

You don't need to create another array and then push into it. Just use map() on the employments and change both the properties. Moreover use a separate function for creating 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)
                          })
                    )

    }
}
Related