anijit anijit - 10 months ago 46
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
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

When it is
it prints the corresponding value. But, if it is
it prints
as there is no matching value.
How to fix it ??

Answer Source

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)

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);