Skip to content

Instantly share code, notes, and snippets.

@dheerajsuthar
Created December 13, 2018 13:36
Show Gist options
  • Save dheerajsuthar/f247483e9979a7f6eeb9f0c5573d4343 to your computer and use it in GitHub Desktop.
Save dheerajsuthar/f247483e9979a7f6eeb9f0c5573d4343 to your computer and use it in GitHub Desktop.
Mutable version
let users = [
{
name: {
first: 'John',
last: 'Galt'
},
email: '[email protected]',
age: 30
},
{
name: {
first: 'Mickey',
last: 'Mouse'
},
email: '[email protected]',
age: 90
},
{
name: {
first: 'Charlie',
last: 'Chaplin'
},
email: '[email protected]',
age: 129
},
];
const ChangeUserFirstName = 'John',
ChangeUserLastName = 'Galt',
ChangeAge = 38;
// Following change spoils the existing object for everyone. Other users won't
// have any way of knowing the original state.
users.forEach(user => {
if (user.name.first === ChangeUserFirstName &&
user.name.last === ChangeUserLastName) {
user.age = 38;
}
});
console.log('users', users);
// Find the changed record.
const changedRecord = users.filter(user => (user.name.first === ChangeUserFirstName &&
user.name.last === ChangeUserLastName));
console.log('changedRecord', changedRecord);
// No way to retrieve original record now :(
// const originalRecord = users.filter(user=>user.name.first === ChangeUserFirstName &&
// user.name.last === ChangeUserLastName);
// console.log('originalRecord', originalRecord);
// returns same record as changedRecord
// ============Output============
//   npx babel-node --presets @babel/preset-env mutability.js
// users [ { name: { first: 'John', last: 'Galt' },
// email: '[email protected]',
// age: 38 },
// { name: { first: 'Mickey', last: 'Mouse' },
// email: '[email protected]',
// age: 90 },
// { name: { first: 'Charlie', last: 'Chaplin' },
// email: '[email protected]',
// age: 129 } ]
// changedRecord [ { name: { first: 'John', last: 'Galt' },
// email: '[email protected]',
// age: 38 } ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment