如何不敏感地搜索JSON文件的密钥大小写

Ani*_*Sau 9 javascript json node.js

我有一个像下面的JSON对象,

"Data Center": {
        "TMSLevel2": {
            "Comp-NX2/4/5/6K": "NX2/4/5/6K",
            "Comp-NX3K": "NX3K",
            "Comp-NX7K": "NX7K",
            "Comp-NX9K": "NX9K",
            "Comp-ACI": "ACI"
         }
}
Run Code Online (Sandbox Code Playgroud)

我将文件命名为map.jsvar map = require ('./map.js')从Node JS 导入它.我正在访问它console.log(map["Data center"]["TMSLevel2"][name]).现在名称是"Comp-NX3K""Comp-NX3k""Comp-nx3K".

当它"Comp-NX3K"打印相应的值.但是,如果它"Comp-nx3K"打印,"undefined"因为没有匹配的值.怎么解决?

jkr*_*ris 11

您可以创建一个函数来执行正则表达式检查,如下所示:

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;
    }, []);
}
Run Code Online (Sandbox Code Playgroud)

示例用法

let result = findValueOfProperty(map["Data center"]["TMSLevel2"], name)
console.log(result);
Run Code Online (Sandbox Code Playgroud)

你可以更进一步,使它成为原型功能

Object.prototype.find = function(propertyName) {
    return findValueOfProperty.bind(this, this);
};
Run Code Online (Sandbox Code Playgroud)

并称之为

var result = map["Data center"]["TMSLevel2"].find(name);
console.log(result);
Run Code Online (Sandbox Code Playgroud)


Jim*_* B. 8

这是一个快速的黑客:

let map2 = JSON.parse(JSON.stringify(map).toUpperCase());
console.log(map2["DATA CENTER"]["TMSLEVEL2"]["COMP-NX3K"]);
Run Code Online (Sandbox Code Playgroud)

这会丢失对象中值的情况,但看起来它们都是大写的,所以也许没有问题?


cwa*_*ole 7

JavaScript对象属性区分大小写,这意味着JSON键也区分大小写.但是,假设你没有一个庞大的名单,那么你可以使用Object.keys,Object.values并创建一个是小写字母索引.

var searchedFor = ("NX3K").toLowerCase(); // make sure to have them match case
var data =  {
            "Comp-NX2/4/5/6K": "NX2/4/5/6K",
            "Comp-NX3K": "NX3K",
            "Comp-NX7K": "NX7K",
            "Comp-NX9K": "NX9K",
            "Comp-ACI": "ACI"
         };
var iKeys = Object.keys(data) // this is a list of all of the attributed above (Comp-…)
               .map( // this calls a function on every member of an Array
                  function(x){ // this function returns a lower cased version of whatever
                               // value it was given
                      return x.toLowerCase();});

// iKeys is now an array of lower-cased keys.
var myValue = Object.values(data)[
                      // wherever the searched for element shows up, 
                      // will correspond to that value.
                      iKeys.indexOf(searchedFor)];
Run Code Online (Sandbox Code Playgroud)

我必须警告你,上面只会匹配密钥的第一个实例.因此,如果有案件Comp-NX9KComp-nx9k你只有一次.