Search code examples
javascriptfor-loopobjectif-statement

Assume I have 2 objects & according to them I want new object


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
    }
}

Solution

  • 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.