English version
First time writing a post in DEV.to, accepting all the recommendations, thank you, I hope you find it helpful and learning, this was an interview question February 2020.
MAP, MUTATING / UPDATING THE ORIGINAL ARRAY
const persons= [
{name: 'Adrian', age: 19},
{name: 'Adriana', age: 10},
{name: 'Erica', age: 29},
{name: 'Eric', age: 23}];
/** Here you are modifying the object (person) of the original array.
||
\/ */
let newPersons= persons.map((person) => {
person.age = 18,
person.name = person.name.toUpperCase()
return person;
});
console.log('persons', persons);
console.log('newPersons', newPersons);
MAP, WITHOUT MUTATE / UPDATING THE ORIGINAL ARRAY
const persons= [
{name: 'Adrian', age: 19},
{name: 'Adriana', age: 10},
{name: 'Erica', age: 29},
{name: 'Eric', age: 23}];
/**
What changes, is only to use spread operator (...person)
in this part to use a person clone, instead of the original one,
so we avoid modifying the original array and its properties
as such because we have a new array (newPersons).
spread operator
||
\/ */
let newPersons= persons.map(({...person}) => {
person.age = 18,
person.name = person.name.toUpperCase()
return person;
});
console.log('persons', persons);
console.log('newPersons', newPersons);
Versión en español
Primera vez que hago un post en DEV.TO, acepto todas las recomendaciones, gracias, espero les ayude y sirva de aprendizaje, esto es de una entrevista real de javascript de Febrero 2020
MAP, MUTANDO / ACTUALZIANDO EL ARRAY ORIGINAL
const persons= [
{name: 'Adrian', age: 19},
{name: 'Adriana', age: 10},
{name: 'Erica', age: 29},
{name: 'Eric', age: 23}];
/** Aqui modificamos el objeto (person) del array original.
||
\/ */
let newPersons= persons.map((person) => {
person.age = 18,
person.name = person.name.toUpperCase()
return person;
});
console.log('persons', persons);
console.log('newPersons', newPersons);
MAP, SIN MUTAR / ACTUALIZAR EL ARRAY ORIGINAL
const persons= [
{name: 'Adrian', age: 19},
{name: 'Adriana', age: 10},
{name: 'Erica', age: 29},
{name: 'Eric', age: 23}];
/**
Lo que cambia, es solo usar el operador de propagación (... person)
en esta parte para usar un clon de person, en lugar del original,
así que evitamos modificar el array original y sus propiedades
como tal porque tenemos un nuevo array (newPersons).
spread operator
||
\/ */
let newPersons= persons.map(({...person}) => {
person.age = 18,
person.name = person.name.toUpperCase()
return person;
});
console.log('persons', persons);
console.log('newPersons', newPersons);
JAVASCRIPT MAP DESCRIPTION ENGLISH
JAVASCRIPT SPREAD OPERATOR DESCRIPTION ENGLISH
JAVASCRIPT MAP DESCRIPCIÓN ESPAÑOL
JAVASCRIPT SPREAD OPERATOR DESCRIPCIÓN ESPAÑOL
Top comments (1)
Buena esa, la del spread en el parámetro de la arrow es bastante buena idea. Gracias!