我有下面的对象,如果新值与旧值不同则想要布尔标志为真,如果不是
则为假原始对象:
{
userName: 'user@gmail.com',
email: 'rakesh@gmail.com',
firstName: 'Naresh',
lastName: 'Kumar',
oldEmail: 'kuamr@gmail.com',
oldFirstName: 'Rakesh',
oldLastName: 'Kumar'
}
转型后:
{
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'
}
有没有办法在lodash中做到这一点?
答案 0 :(得分:1)
您可以使用带有键的数组来检查属性。
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; }