How to change the value of an object array?

Asked

Viewed 326 times

2

I need to multiply each user’s age by 2 and change it in each object. How do I change the value?

const usuarios = [
    { nome: 'Diego', idade: 23, empresa: 'Rocketseat' },
    { nome: 'Gabriel', idade: 15, empresa: 'Rocketseat' },
    { nome: 'Lucas', idade: 30, empresa: 'Facebook' },
];
for (let usuario of usuarios) {
    const multiplicarIdade = usuario.idade * 2
}
console.log(usuarios)

Expected result:

// Resultado:
[
 { nome: 'Diego', idade: 46, empresa: 'Rocketseat' },
 { nome: 'Gabriel', idade: 30, empresa: 'Rocketseat' },
]
  • So, the original proposal was to multiply the age of each user by 2 and finally return the age of users under 50. I used everyone’s tip, but like ḿap creates the copy of the original, but with new values, within this scenario it became more interesting to use it.

4 answers

6


Boy I believe the easiest way to settle this is with a map, for example :

     const novosUsuarios = usuarios.map(u => ({ ...u, idade: u.idade * 2 }));
     console.log(novosUsuarios);

made a example running, if you want to check

3

You almost right, just needed to put the result of multiplication in the property idade:

const usuarios = [
    { nome: 'Diego', idade: 23, empresa: 'Rocketseat' },
    { nome: 'Gabriel', idade: 15, empresa: 'Rocketseat' },
    { nome: 'Lucas', idade: 30, empresa: 'Facebook' },
];
for (let usuario of usuarios) {
    usuario.idade *= 2; // <--- aqui
}
console.log(usuarios);

In the case, usuario.idade *= 2 is the same as doing usuario.idade = usuario.idade * 2. That is, I change the value of age, which becomes twice the original value.

One of the answers suggested to use map, which also works. The difference is that map returns another array with modified values. So the solutions are not equivalent, and to decide which one to use will depend on what you need. If you want to change the array values themselves, use the loop above. If you want to keep the original values and create a copy with the modified values, use map.

2

The simplest way is like this:

const usuarios = [
    { nome: 'Diego', idade: 23, empresa: 'Rocketseat' },
    { nome: 'Gabriel', idade: 15, empresa: 'Rocketseat' },
    { nome: 'Lucas', idade: 30, empresa: 'Facebook' },
];

usuarios.forEach(usuario => usuario.idade = usuario.idade * 2);

console.log(usuarios);

0

I did it with a loop going through the entire list, see if it works and if you can understand how it works

const usuarios = [
    { nome: 'Diego', idade: 23, empresa: 'Rocketseat' },
    { nome: 'Gabriel', idade: 15, empresa: 'Rocketseat' },
    { nome: 'Lucas', idade: 30, empresa: 'Facebook' },
];

for (i = 0; i < usuarios.length; i++) {
    var aux = usuarios[i]['idade'] * 2;
    usuarios[i]['idade'] = aux;
}

Browser other questions tagged

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