skip to Main Content

I’m working on a TypeScript project where I need to compare two objects with potentially nested structures and identify the fields that have changed between them. For instance, consider an old object oldObject with fields like name, age, city, friends (an array), and possibly nested objects within. Now, I have a new object newObject with the same structure, but with potentially updated values for some fields.

Here’s an example:

const oldObject = { name: 'John', age: 30, city: 'New York', friends: ['ali', 'qasim'], def: { 'a': 1, 'b': 2 } };
const newObject = { name: 'John', age: 35, city: 'New York', friends: ['ali', 'haider'] };

In this scenario, I need to be able to identify and extract the changed fields between oldObject and newObject, along with their new values, retaining the nested structure.

I’ve attempted a comparison function, but it’s not correctly handling nested structures and arrays. How can I implement a solution in TypeScript that accurately identifies the changed fields while preserving the nested structure of the objects?

  • I’m looking for a TypeScript function or approach that can accurately identify changed fields between two objects with nested structures.
  • The function should correctly handle nested objects and arrays, identifying changes within them.
  • The solution should be efficient and scalable for objects of varying sizes and complexities.
  • Any insights or improvements on the provided sample function would be greatly appreciated.
  • Clear explanations and examples would be helpful for better understanding and implementation.

2

Answers


  1. Chosen as BEST ANSWER

    To accurately identify and compare changed fields in TypeScript objects with nested structures, you can utilize a recursive approach. Here's how you can implement a function to achieve this:

      function findChangedFields(oldObj: any, newObj: any): { old: any, new: any } {
    const changedFields: { old: any, new: any } = { old: {}, new: {} };
    
    for (const key in oldObj) {
        if (oldObj.hasOwnProperty(key)) {
            if (!newObj.hasOwnProperty(key)) {
                changedFields.old[key] = oldObj[key];
                changedFields.new[key] = undefined; // Field does not exist in new object
            } else if (Array.isArray(oldObj[key]) && Array.isArray(newObj[key])) {
                if (JSON.stringify(oldObj[key]) !== JSON.stringify(newObj[key])) {
                    changedFields.old[key] = oldObj[key];
                    changedFields.new[key] = newObj[key];
                }
            } else if (typeof oldObj[key] === 'object' && typeof newObj[key] === 'object') {
                const nestedChanges = findChangedFields(oldObj[key], newObj[key]);
                if (Object.keys(nestedChanges.old).length > 0 || Object.keys(nestedChanges.new).length > 0) {
                    changedFields.old[key] = nestedChanges.old;
                    changedFields.new[key] = nestedChanges.new;
                }
            } else {
                if (oldObj[key] !== newObj[key]) {
                    changedFields.old[key] = oldObj[key];
                    changedFields.new[key] = newObj[key];
                }
            }
        }
    }
    
    // Check for new keys in newObj
    for (const key in newObj) {
        if (newObj.hasOwnProperty(key) && !oldObj.hasOwnProperty(key)) {
            changedFields.old[key] = undefined; // Field does not exist in old object
            changedFields.new[key] = newObj[key];
        }
    }
    
    return changedFields;
    }
    
    // Example usage:
    const oldObject = { name: 'John', age: 30, city: 'New York', friends: ['ali', 'qasim'], def: { 'a': 1, 'b': 3 }, ng: { a: { d: 1 } } };
    const newObject = { name: 'John', age: 35, city: 'New York', friends: ['ali', 'haider'], def: {}, ng: { a: {} } };
    
    const changedFields = findChangedFields(oldObject, newObject);
    console.log(changedFields);

    This function recursively traverses through the objects and arrays to compare their elements. If a difference is found, it records the changed field along with its new value in the changedFields object.

    You can test this function with your sample objects oldObject and newObject to see the changed fields along with their new values.


  2. const oldObject = { name: 'John', age: 30, city: 'New York', friends: ['ali', 'qasim'], def: { 'a': 1, 'b': 2 } };
    
    const newObject = { name: 'John', age: 35, city: 'New York', friends: ['ali', 'haider'] };
    let oldobj = Object.keys(oldObject)
    console.log(oldobj)
    let newobj = Object.keys(newObject)
    console.log(newobj)
    let result = oldobj.filter(x => !newobj.includes(x));
    
    if(result.length> 0){
        console.log(oldObject.def)
    }

    // finding keys in 2 arrays . and checking keys are same in both araays or not

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search