Как сравнить два объекта и занести свойства объектов в которых произошли изменения в другой объект?

Это первый объект

  action: 'U',
  author: 'DZC\\PavelK',
  data: {
    accreditationSheetDate: '2021-11-15T00:00:00',
    accreditationSheetNumber: '100',
    accreditationTerm: {
      value: '6 gadi',
      valueEn: '6 years',
    },
    accreditationTermId: '30a827ff-dd9e-4809-bd37-7b619c060aaf',
    accreditationFrom: '2021-11-12T00:00:00',
    accreditationTo: '2021-11-26T00:00:00',
    director: 'asdasdasdasd',
    justification: 'zxfccvxcbn,m',
  },
  date: '2021-11-08T12:44:51.433',
  id: 22,
};

Это второй объект

  action: 'I',
  author: 'DZC\\PavelK',
  data: {
    accreditationSheetDate: '2021-11-17T00:00:00',
    accreditationSheetNumber: '110',
    accreditationTerm: {
      value: '8 gadi',
      valueEn: '8 years',
    },
    accreditationTermId: '30a827ff-dd9e-4567-bd37-7b619c060aaf',
    accreditationFrom: '2021-11-15T00:00:00',
    accreditationTo: '2021-11-25T00:00:00',
    director: 'asdasdasdasd',
    justification: 'zxfccvxcbn,m',
  },
  date: '2021-11-09T14:48:51.433',
  id: 23,
};

Мы должны получить объект вида {filedName, previousValue, currentValue, dateOfChange, author} с названиями полей, которые были изменены


Ответы (1 шт):

Автор решения: Алексей

const obj1 = {
  action: 'U',
  author: 'DZC\\PavelK',
  data: {
    accreditationSheetDate: '2021-11-15T00:00:00',
    accreditationSheetNumber: '100',
    accreditationTerm: {
      value: '6 gadi',
      valueEn: '6 years',
    },
    accreditationTermId: '30a827ff-dd9e-4809-bd37-7b619c060aaf',
    accreditationFrom: '2021-11-12T00:00:00',
    accreditationTo: '2021-11-26T00:00:00',
    director: 'asdasdasdasd',
    justification: 'zxfccvxcbn,m',
  },
  date: '2021-11-08T12:44:51.433',
  id: 22,
};

const obj2 = {
  action: 'I',
  author: 'DZC\\PavelK',
  data: {
    accreditationSheetDate: '2021-11-17T00:00:00',
    accreditationSheetNumber: '110',
    accreditationTerm: {
      value: '8 gadi',
      valueEn: '8 years',
    },
    accreditationTermId: '30a827ff-dd9e-4567-bd37-7b619c060aaf',
    accreditationFrom: '2021-11-15T00:00:00',
    accreditationTo: '2021-11-25T00:00:00',
    director: 'asdasdasdasd',
    justification: 'zxfccvxcbn,m',
  },
  date: '2021-11-09T14:48:51.433',
  id: 23,
};

const convert = (obj1, obj2) => {
  return Object.entries(obj1).reduce((acc, [key, value]) => {
    if (value instanceof Object) {
      return { ...acc, [key]: convert(value, obj2[key]) };
    } else if (value !== obj2[key]) {
      return { ...acc, [key]: { prev: value, curr: obj2[key] } };
    } else return { ...acc };
  }, {});
};

console.log(convert(obj1, obj2));
Ну а дальше уже под свои нужды.

→ Ссылка