Requisito: Compare la diferencia entre dos objetos y devuelva el objeto de diferencia.
Esta función que hice encontrará valores nuevos o modificados y nuevos elementos de la matriz.
function isObject(object) { return object !== null && typeof object === 'object' && !Array.isArray(object); } function compareObject(data, lastData, diff = {}) { const keys = Object.keys(data); for (let key of keys) { if (lastData === undefined) { lastData = {}; } if (lastData[key] === undefined) { diff[key] = JSON.parse(JSON.stringify(data[key])); continue }; if (Array.isArray(data[key])) { if (data[key].length !== lastData[key].length) { const diffArr = data[key].filter((item, index) => lastData[key][index] === undefined) diff[key] = diffArr; continue } }; if (!isObject(data[key]) && JSON.stringify(data[key]) !== JSON.stringify(lastData[key])) { diff[key] = data[key]; continue } if (isObject(data[key])) { if (Object.keys(compareObject(data[key], lastData[key])).length !== 0) { diff[key] = compareObject(data[key], lastData[key]); continue } }; } return diff }ejemplo de origen de la siguiente manera:
const oldData = { account_info: { age: 30, favor: ["coding", "music"], cars: [{ brand: 'toyota', count: 1 }], room: { A01: "test1", } }, server: { os: "Linux", cloud: "gcp" } } const newData = { account_info: { age: 30, favor: ["coding", "music", "see movie"], cars: [{ brand: 'toyota', count: 2 }, { brand: 'KIA', count: 1 }], room: { A01: "test2", A02: "black", A03: "white" } }, "server": { "os": "Linux", } } // result(without first object value changed in array) // { // account_info: { // favor: [ 'see movie' ], // cars: [ { brand: 'KIA', count: 1 } ], // room: { A01: 'test2', A02: 'black', A03: 'white' } // } // } ¿Pero la nueva demanda también es averiguar qué objeto en la matriz ha cambiado solo el valor?
¿Cómo puedo extender esta función?
¡¡Gracias!!