2017-10-19 35 views
0

我有一個大問題。我想創建一個函數來刪除兩個JSON文件之間相等的'部分',函數的輸出具有相同的結構,但沒有'相等部分'。刪除兩個JSON之間相等的密鑰

一個例子,我有一個DOM樹的JSON版本,我想只保留頁面之間的差異(除去導航頁腳...)

const a = { 
    id: '1', 
    child: [ 
    { 
    id: '2', 
    child: [ 
     { 
     id: '1' 
     }, 
     { 
     id: '2' 
     } 
    ] 
    }, 
    { 
    id: '3', 
    child: [ 
     { 
     id: '1' 
     }, 
     { 
     id: '5' 
     } 
    ]  
    } 
    ] 
} 

而且

const b = { 
    id: '1', 
    child: [ 
    { 
    id: '2', 
    child: [ 
     { 
     id: '1' 
     }, 
     { 
     id: '4' 
     } 
    ] 
    }, 
    { 
    id: '3', 
    child: [ 
     { 
     id: '1' 
     }, 
     { 
     id: '4' 
     } 
    ]  
    } 
    ] 
} 

帶功能

diff(a, b) 

這個結果

{ 
    id: '1', 
    child: [ 
    { 
    id: '2', 
    child: [ 
     { 
     id: '2' 
     } 
    ] 
    }, 
    { 
    id: '3', 
    child: [ 
     { 
     id: '5' 
     } 
    ]  
    } 
    ] 
} 

我創造了這個基於遞歸函數

const diff = (a, b) => { 
    if (Array.isArray(a)) { 

    } 

    if (typeof a === 'object') { 
    // ... 
    extract(a.child, b.child); 
    } 
} 

我該怎麼辦呢?有沒有npm軟件包?或與JSON路徑?我想創建一個函數,它可以刪除兩個JSON文件之間相等的「部分」,而函數的輸出具有相同的結構,但沒有「相等部分」。

+1

看看https://www.npmjs.com/package/deep-diff。 – nicooga

+0

我想刪除相同的部分,但這個軟件包顯示我的差異 –

+1

只是FYI但這些不是json文件,這些都是javascript對象。 JSON是JavaScript Object Notation,用於將javascript對象作爲字符串傳輸或存儲。 – Marie

回答

0

我假設你不能保證id /值對的順序?

我建議你先遞歸合併每一層,然後通過並刪除重複項。

編輯過的代碼從遞歸函數

let c = [] // merged structure 
for (var i=0; i<a.length; i++) 
{ 
    for (let j=0; j<b.length; j++) 
    { 
     if (a[i].id === j[i].id) { 
     c[i] = { id: a[i].id, child: a[i].child.concat(b[i].child) } 
     // next, sort the c[i].child, and 
     // loop through c[i].child and recur over any cases where 
     // c[i].child[k].id === c[i].child[k+1].id 
     // at the end, go back up the chain removing any structs where the 
     // id is a duplicate and has no children left 
     } 
    } 
} 
+0

示例代碼? –

+0

肯定 - 編輯上面 – tcmoore

+0

我想刪除a和b之間的等於對象 –