KoboldMines
KoboldMines

Reputation: 480

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

Upvotes: 2

Views: 866

Answers (2)

Anon
Anon

Reputation: 39

Nina Scholz correctly points out that a solution is to create a copy of each object within the function in the map method and alludes to why this is necessary: The map method is creating a new array of objects, but those objects share the same references as the objects in the original array. Thus, any changes made to the objects reflects in both arrays.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

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; }

Upvotes: 1

Related Questions