Array n object manipulations(Mutations, Non-mutating arrays in ES5 and ES6)
by Divya
JavaScript
var persons = [
{
name: "name1",
isGraduated: true
},
{
name: "name2",
isGraduated: false
},
{
name: "name3",
isGraduated: false
},
];
var newPerson = {
name: "name4",
isGraduated: false
}
function updatePersons(newObj) {
//Avoiding Array mutations
//return persons.concat(newObj);//ES5
return [
...persons,
newObj
]//ES6
//Array mutations which we shouldn't prefer
//return persons.push(newObj);
}
var PersonsafterAdding = updatePersons(newPerson);
console.log(`AfterAdding:
${JSON.stringify(PersonsafterAdding)}`);
console.log(`personsAfterAdding:
${JSON.stringify(persons)}`);
function deletePerson(index) {
//Avoiding array mutations
//ES5
/* return [
persons.slice(0, index).concat(persons.slice(index+1))
] */
//ES6
return [
...persons.slice(0, index),
...persons.slice(index+1)
]
//Array mutation which we shouldn't prefer
//return persons.splice(index, 1);
}
var afterDelete = deletePerson(1);
console.log(`afterDelete:
${JSON.stringify(afterDelete)}`);
console.log(`personsAfterDelete:
${JSON.stringify(persons)}`);
var afterEdit = editPersons(1);
function editPersons(id) {
//Avoiding array mutations
//ES6
return persons.map((person, index) => {
//ES6
//return (index === id) ? {...person, isGraduated: true, newProp: true} : person;
//ES5
/* if(index === id) {
person = {
isGraduated: true,
newProp: true
}
}
return person; */
/* OR
return Object.assign({}, person, {isGraduated: !person.isGraduated, newProp: true}; */
//Array mutations
//return persons.splice(id, 1, {name: person.name, isGraduated: !person.isGraduated, newProp: true});
});
}
console.log(`afterEdit:
${JSON.stringify(afterEdit)}`);
console.log(`personsAfterEdit:
${JSON.stringify(persons)}`);