2

I use the deep-diff Node.js library for comparison of two JSONs. There is also pre-filter condition for omitting few fields for comparison. If my pre-filter condition is multiple attributes, how would I specify that? In the given example, the pre-filter attribute is name. If I want to add one or more attributes, how would I specify that. Thanks in advance.

var diff = require('deep-diff').diff;

        var lhs = {
            name: 'my object',
            description: 'it\'s an object!',
            details: {
                it: 'has',
                an: 'array',
                with: ['a', 'few', 'elements']
            }
        };

        var rhs = {
            name: 'updated object',
            description: 'it\'s not an object!',
            details: {
                it: 'has',
                an: 'array',
                with: ['a', 'few', 'more', 'elements', {
                    than: 'before'
                }]
            }
        };


        var differences = diff(lhs, rhs, function(path, key) {

            return key === 'name';
        });

        console.log(differences);
DAXaholic
  • 33,312
  • 6
  • 76
  • 74
jojo
  • 395
  • 3
  • 14

1 Answers1

3

If I understood you correctly, then it should be as simple as adding an or (||). For example, do ignore description as well you could write:

var differences = diff(lhs, rhs, function(path, key) {
    return key === 'name' || key === 'description'; 
});

Of course, as you start ignoring lots of items you may want to introduce an array of properties / paths you want to ignore and then simply check in the pre-filter if the current property should be ignored. So a more generic way with an array could be like this:

var ignoredProperties = ['prop1', 'prop2', 'prop3'];
var differences = diff(lhs, rhs, function(path, key) {
    return ignoredProperties.indexOf(key) >= 0;
});

With ECMAScript 2016 there are also Set objects which would be better in this case but as this is not widely implemented yet I would use the code above.

DAXaholic
  • 33,312
  • 6
  • 76
  • 74
  • can you help me doing this in a more generic way instead of giving it a hard coded value, say passing a function of array of values. TIA – jojo Jul 14 '16 at 04:54
  • var inputArray = ["name", "description"]; var differences = diff(lhs, rhs, function(path, key) { var truthValue = false; for (var i in inputArray) { if (key === i) { truthValue = true; } } return truthValue; }); – jojo Jul 14 '16 at 05:02
  • why I am not getting the key. I am only getting the path value in diff – Mallikarjuna Nov 04 '19 at 15:29