Node js:在Json数组中搜索动态json对象

时间:2018-07-17 05:46:10

标签: node.js

我有以下JSON数据,

var configs =   [{
                    "port" : "3003", 
                    "mongoURI" : "mongodb://localhost:27017/serviceRequest", 
                    "MQ" : "RMQ", 
                    "logLevel" : "2", 
                    "version" : "1.1", 
                    "created" : "03-06-2018 03:11:00 PM", 
                    "active" : "N"
                }, 
                {
                    "port" : "3004", 
                    "mongoURI" : "mongodb://localhost:27017/serviceRequest", 
                    "MQ" : "IMQ", 
                    "logLevel" : "1", 
                    "version" : "1.2", 
                    "created" : "07-06-2018 03:11:00 PM", 
                    "active" : "Y"
                }, 
                {
                    "port" : "3003", 
                    "mongoURI" : "mongodb://localhost:27017/serviceRequest", 
                    "MQ" : "Apache Cafka", 
                    "logLevel" : "3", 
                    "version" : "1.3", 
                    "created" : "03-06-2018 03:11:00 PM", 
                    "active" : "Y"
                }, 
                {
                    "port" : "3003", 
                    "mongoURI" : "mongodb://localhost:27017/serviceRequest", 
                    "MQ" : "RMQ", 
                    "logLevel" : "3", 
                    "version" : "1.4", 
                    "created" : "03-06-2018 03:11:00 PM", 
                    "active" : "Y"
                }]

而且,我有以下动态json对象。

var cloudParam = {
        "MQ" : "RMQ",
        "logLevel" : "2"
    }

动态方式,cloudParam中的键值对不固定。现在它有MQ & LogLevel,但是下次它将是MQ,loglevel & version-基本上它是不固定的。

所以,我想找到包含cloudParam的json对象。 我尝试了下面的代码,但没有得到json obj。

for(i = 0; i < configs.length ; i++){
    var configItem = configs[i];
    for (var item in cloudParam) {        
        if(item in configItem && configItem[item] === cloudParam[item]){
            console.log("Present");
        } else {
            console.log("Not Present");
        }
    }    
}

EDIT:@ Aks,感谢您的回答,如果我想找到匹配文档的索引,怎么找到它?

1 个答案:

答案 0 :(得分:0)

使用filterevery。 如果您只需要一场比赛,则可以使用.find代替.filter

var cloudParam = {
  MQ: "RMQ",
  logLevel: "2"
};

console.log(
  configs.filter(config =>
    Object.keys(cloudParam).every(key => config[key] === cloudParam[key])
  )
);