Try   HackMD

用 javascrpit 比較兩個 json 的差異,並且取得差異內容

問題

兩個json的差異直接印出來不太好找,想要用程式比對只看差異的部分

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

解法

https://codepen.io/not0000/pen/oNePJXm

const obj1 = {
    "id": 50,
    "name": "AIK",
    "description": "Hejja!",
    "tasks": [{ 'foo': 'bar' }],
    "another1":"you can't see me"
};
const obj2 = {
    "id": 50,
    "name": "DIFF",
    "description": "Hejja!",
    "tasks": [{ 'foo': 'zaz' }],
    "another2":"by john cena"
};

function diff(obj1, obj2) {
    const result = {};
    if (Object.is(obj1, obj2)) {
        return undefined;
    }
    if (!obj2 || typeof obj2 !== 'object') {
        return obj2;
    }
    Object.keys(obj1 || {}).concat(Object.keys(obj2 || {})).forEach(key => {
        if (obj2[key] !== obj1[key] && !Object.is(obj1[key], obj2[key])) {
            result[key] = obj2[key];
        }
        if (typeof obj2[key] === 'object' && typeof obj1[key] === 'object') {
            const value = diff(obj1[key], obj2[key]);
            if (value !== undefined) {
                result[key] = value;
            }
        }
    });
    return result;
}
console.log(JSON.stringify(diff(obj1, obj2), null, 2))

注意事項

如果是來源有的屬性,但比較對象沒有,那不會顯示出來的,請見範例的 another1 和 another2 的情形

參考來源

link