0

I have a JSON version of a DOM tree and I want keep only the difference between pages (remove nav footer ...)

Example:

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

And

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

With a function

diff(a, b)

This result

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

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

I created this based on recursive function

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

  }

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

How do I do this? Is there an npm package? or with JSON Path? I want to create a function that remove the equal 'parts' between two JSON files with the output of the function having the same structure, but without the 'equal parts' only difference.

N-Alpr
  • 336
  • 2
  • 11
  • That's not JSON. JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Oct 19 '17 at 21:04

1 Answers1

0

You can do this a little differently, this should get you the right values.

function diff(obj1, obj2) {
  var ret = {};
  for(var i in obj2) {
    if(!obj1.hasOwnProperty(i) || obj2[i] !== obj1[i]) {
      ret[i] = obj2[i];
    }
  }
  return ret;
};

See the code here with your example data https://jsbin.com/toboto/edit?js,console

This solution is not recursive though. Alternatively, for a deep difference I recommend checking out this library https://github.com/flitbit/diff

kyle
  • 2,563
  • 6
  • 22
  • 37