Home > Enterprise >  Filter similar JSON keys and compare using Lodash
Filter similar JSON keys and compare using Lodash

Time:11-04

Trying to filter localJSON based on remoteJSON and create a new localJSONFiltered based on those keys present in the remoteJSON. And then finally comparing the values.

Script

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

remoteJSON data. and localJSON

const remoteJSON = {"address": "LAN",
                    "city": "LAN-CITY",
                    "code": "A1"       
                    };

const localJSON = { "city": "LAN-CITY",
                    "code": "A1",
                    "address": "LAN",
                    "extraKey":"I am not required..please remove me while comparing"
                   }
              
console.log( _.isEqual(a, b) ); // false

Expecting to remove the extraKey property from the localJSON i.e., localJSON need to have only those properties which is in remoteJSON and then compare the values.

const remoteJSON = {"address": "LAN",
                    "city": "LAN-CITY",
                    "code": "A1"       
                    };
const localJSONRemoving = _.omit(localJSON, ['extraKey']));
const localJSONAfterRemoving = { "city": "LAN-CITY",
                    "code": "A1",
                    "address": "LAN"
                   }
              
console.log( _.isEqual(a, b) ); // true

My localJSON has over 30 properties. So hardcoding all the properties looks bad.

CodePudding user response:

Something like this, continuing the use of lodash:

const _ = require("lodash");

const a = {
  address: "LAN",
  city: "LAN-CITY",
  code: "A1"
};

const b = {
  city: "LAN-CITY",
  code: "A1",
  address: "LAN",
  extraKey: "I am not required..please remove me while comparing",
};

// Goal: test if a and b are the same except that we ignore extra keys in b

const extraKeys = _.filter(_.keys(b), (x) => !_.keys(a).includes(x));
console.log(_.isEqual(a, _.omit(b, extraKeys)));
  • Related