Search code examples
javascriptnode.jsjsonecmascript-6lodash

NodeJS deep nested json comparison case insensitive key/value pair


I want to compare two nested json in NodeJS, json key position can change and also key/value comparison should bee case insensitive

I'm using deep-equal NodeJS module, but it's only working for case sensitive comparison

let json1 = {
  "type": "NEW",
  "users": [{
    "id": "dskd3782shdsui",
    "email": "[email protected]"

  }],
  "ordered": [{
    "productId": "SHFDHS37463",
    "SKU": "ffgh"
  }]
}

let json2 = {
  "type": "NEW",
  "users": [{
    "id": "dskd3782shdsui",
    "email": "[email protected]"

  }],
  "ordered": [{
    "productId": "SHFDHS37463",
    "SKU": "ffgh"
  }]
}

var deepEqual = require('deep-equal')

console.log('==', deepEqual(
  json1,
  json2
))

Above code is working but if I change json2 email to [email protected] or email key to EMAIL it's returning false I want case insensitive comparison.


Solution

  • I got solution for this it will work for both key/value case insensitive and also if we change key position

    var deepEqual = require('deep-equal')
    
    function toLower(a) {
     return JSON.stringify(a).toLowerCase();
    }
    
    
    console.log('==', deepEqual(
        JSON.parse(toLower(json1)),
        JSON.parse(toLower(json2))
    ) )