anijit anijit - 18 days ago 5
Javascript Question

How to search a JSON file's key case insensititvely

I have a JSON object like below,

"Data Center": {
"TMSLevel2": {
"Comp-NX2/4/5/6K": "NX2/4/5/6K",
"Comp-NX3K": "NX3K",
"Comp-NX7K": "NX7K",
"Comp-NX9K": "NX9K",
"Comp-ACI": "ACI"
}
}


I named the file as
map.js
and import it by
var map = require ('./map.js')
from Node JS.
I am accessing it like
console.log(map["Data center"]["TMSLevel2"][name])
. Now the name be
"Comp-NX3K"
or
"Comp-NX3k"
or
"Comp-nx3K"
.

When it is
"Comp-NX3K"
it prints the corresponding value. But, if it is
"Comp-nx3K"
it prints
"undefined"
as there is no matching value.
How to fix it ??

Answer

You could create a function to do a regex check like so:

function findValueOfProperty(obj, propertyName){
    let reg = new RegExp(propertyName, "i"); // "i" to make it case insensitive
    return Object.keys(obj).reduce((result, key) => {
        if( reg.test(key) ) result.push(obj[key]);
        return result;
    }, []);
}

Eample Usage

let result = findValueOfProperty(map["Data center"]["TMSLevel2"], name)
console.log(result);

You can bring it one step further my making it a prototype function

Object.prototype.find = function(propertyName) {
    return findValueOfProperty.bind(this, this);
};

And call it like so

var result = map["Data center"]["TMSLevel2"].find(name);
console.log(result);