skip to Main Content
const data = {
    name : "teahyung",
    fatherName : "kim-ji-hyung",
    age : 26
}

const data1 = {
    name : "jangkook",
    fatherName : "kim-ji-hyung",
    age : 23
}

ans = {
    name : {
        old : "teahyung",
        new : "jangkook"
    },
    age : {
        old : 26,
        new : 23
    }
}

2

Answers


  1. function compareData(data, data1) {
        const ans = {};
        for (const key in data) {
            if (data[key] !== data1[key]) {
                ans[key] = { old: data[key], new: data1[key] };
            }
        }
        return ans;
    }
    
    const data = { name: "teahyung", fatherName: "kim-ji-hyung", age: 26 };
    const data1 = { name: "jangkook", fatherName: "kim-ji-hyung", age: 23 };
    
    const ans = compareData(data, data1);
    console.log(ans);
    

    This function takes data and data1 objects and returns the differences between these two objects as an object named ans. The function checks each key in the data object and if the values in data and data1 are different, it adds the old and new values for that key to the ans object.

    Login or Signup to reply.
  2. You should create a function that takes the original and updated objects.

    This function will:

    • Loop over the updated keys
    • Check if the original has the key, and the value if different
    • Add a new key-value pair to the result
    const
      originalData = { name : "teahyung", fatherName : "kim-ji-hyung", age : 26 },
      updatedData  = { name : "jangkook", fatherName : "kim-ji-hyung", age : 23 };
    
    const diff = (original, updated) => {
      const result = {};
      for (let key in updated) {
        if (original.hasOwnProperty(key) && original[key] !== updated[key]) {
         result[key] = { old: original[key], new: updated[key] };
        }
      }
      return result;
    };
    
    const ans = diff(originalData, updatedData);
    
    console.log(ans);
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    Here is a more functional approach:

    const
      originalData = { name : "teahyung", fatherName : "kim-ji-hyung", age : 26 },
      updatedData  = { name : "jangkook", fatherName : "kim-ji-hyung", age : 23 };
    
    const diff = (original, updated) => Object.fromEntries(Object.keys(updated)
      .filter((k) => original.hasOwnProperty(k) && original[k] !== updated[k])
      .reduce((r, k) => r.set(k, { old: original[k], new: updated[k]}), new Map));
    
    const ans = diff(originalData, updatedData);
    
    console.log(ans);
    .as-console-wrapper { top: 0; max-height: 100% !important; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search