0

I have below object and want to boolean flag true if new value different form old value and false if not

Original object:

{ 
  userName: 'user@gmail.com',
  email: 'rakesh@gmail.com',
  firstName: 'Naresh',
  lastName: 'Kumar',   
  oldEmail: 'kuamr@gmail.com',
  oldFirstName: 'Rakesh',
  oldLastName: 'Kumar'
} 

After transformation:

{ 
  userName: 'user@gmail.com',
  email: 'rakesh@gmail.com',
  firstName: 'Naresh',
  lastName: 'Kumar',

  isFirstNameChanged: true,
  isEmailChanged: true,
  isFirstNameChanged: false,

  oldEmail: 'kuamr@gmail.com',
  oldFirstName: 'Rakesh',
  oldLastName: 'Kumar'
} 

Is there any way to do it in lodash?

pirho
  • 11,565
  • 12
  • 43
  • 70
Rakesh Kumar
  • 2,705
  • 1
  • 19
  • 33

1 Answers1

1

You could use an array with the keys for updating the properties with a check.

function update(object) {
    const capitalize = s => s[0].toUpperCase() + s.slice(1);
    
    ['firstName', 'lastName', 'email'].forEach(k => object['is' + capitalize(k) + 'Changed'] = object[k] === object['old' + capitalize(k)]);
}

var object = { userName: 'user@gmail.com', email: 'rakesh@gmail.com', firstName: 'Naresh', lastName: 'Kumar', oldEmail: 'kuamr@gmail.com', oldFirstName: 'Rakesh', oldLastName: 'Kumar' };

update(object);

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392