How to copy an object array in Javascript?

Asked

Viewed 244 times

-2

I have an array of objects and need to create a function that takes this array and returns a new array with new modified objects. See the example below:

function increase_age(users) {
    for (user of users) {
        user.age ++;
    }
    
    return users;
}

const users = [{name: "Lucas", age: 21}, {name: "Maria", age: 23}];
const new_array = increase_age(users);

In the example above, the objects of users are also changed after function call.

What I want is to make a copy of these objects so that they are changed without affecting the original objects. How can I do this in pure Javascript?

  • Dear Jean copy as the suggestions Inkei and change later what you have to change.

  • Thank you William, I had not found this issue on the site.

1 answer

1


One option is to use map, returning a new literal object in each iteration:

function increaseAge(users) {
  return users.map((user) => ({
    ...user,
    age: user.age + 1
  }));
}

const users = [{name: "Lucas", age: 21}, {name: "Maria", age: 23}];
const newArray = increaseAge(users);
console.log(newArray);

I changed the names of the naming convention of snake_case for camelCase, which is the convention most used in Javascript.

  • Thanks Luiz, you helped a lot :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.