2

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

0

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

why not simply Object.assign?
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.