2017-10-19 37 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之间的等于对象 –