Search code examples
javascriptarraysarray-map

Javascript Map Array Object changes original array when try to add property


I map array of objects and try to add property and return new array and log it. But turned out it changes the original array too... Why does this happen? I believe it is some sort of object trick.

var students = [
    { name: 'nika', age: 25 },
    { name: 'goga', age: 11 },
    { name: 'saba', age: 20 },
    { name: 'tedo', age: 35 },
    { name: 'gio', age: 15 },
    { name: 'lasha', age: 5 },
    { name: 'sandro', age: 8 },
];

function solution(arr) {
    let newArr = arr.map(function (item) {
        if (item.age < 18) {
            item.forbidden = true;
        }
        return item;
    });

    console.log(newArr);
    console.log(students);

}

solution(students);

I want solution in ES5


Solution

  • You could create a copy from the object which does not share the same object reference.

    function solution(arr) {
        return arr.map(function (item) {
            item = JSON.parse(JSON.stringify(item));
    
            if (item.age < 18) {
                item.forbidden = true;
            }
            return item;
        });
    }
    
    
    var students = [
        { name: 'nika', age: 25 },
        { name: 'goga', age: 11 },
        { name: 'saba', age: 20 },
        { name: 'tedo', age: 35 },
        { name: 'gio', age: 15 },
        { name: 'lasha', age: 5 },
        { name: 'sandro', age: 8 },
    ];
    
    console.log(solution(students));
    .as-console-wrapper { max-height: 100% !important; top: 0; }