2017-10-19 3 views
0

大きな問題があります。 2つのJSONファイルの間に等しい部分を削除する関数を作成したいと思います。関数の出力は同じ構造を持ちますが、 '等しい部分'はありません。2つのJSON間で等しいキーを削除します

私はDOMツリーのJSONバージョンを持っていると私はページ間の唯一の違いを維持したいの例(NAVフッターを削除...)

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パスを使用していますか?私は同じ構造を持つ関数の出力で2つのJSONファイルの間に等しい 'パーツ'を削除する関数を作成したいと思いますが、 '等しい部分'はありません。

+1

からコードで編集します。 – nicooga

+0

私は同じ部分を削除したいが、このパッケージは私に違いを表示する –

+1

ちょうどFYIしかし、それらはjsonファイルではない、それらはjavascriptオブジェクトです。 JSONはJavaScript Object Notationであり、JavaScriptオブジェクトを文字列として転送または保存するために使用されます。 – Marie

答えて

0

IDと値のペアの順序を保証できないと思いますか?

私はあなたが最初に再帰的に各レイヤーをマージしてから、重複を削除して削除することをお勧めします。

はhttps://www.npmjs.com/package/deep-diffを見てみましょう再帰関数

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の間のequalsオブジェクトを削除したい –

関連する問題