如何使用JavaScript检查JSON密钥是否有特定的单词?

时间:2017-01-17 09:29:40

标签: javascript json

{
  "workbookInformation" : { … },
  "datasources4" : { … },
  "datasources5" : { … },
  "datasources2" : { … },
  "datasources3" : { … },
  "datasources1" : { … }
}

在我的情况下,我需要获取其键具有datasource关键字的对象的数量。

2 个答案:

答案 0 :(得分:2)

您可以使用ES6版本。

var keys = Object.keys(yourobject).filter(x => x.includes('datasource'));

ES5

var keys = Object.keys(yourobject).filter(function (x) {
    return x.includes('datasource');
});

如果您想检查按键,请使用术语“使用x.startsWith('datasource')x.indexOf("datasource")==0

var yourobject = {
  "datasource1": {},
  "datasource2": {},
  "datasource3": {},
  "datasource5": {},
  "datasource4": {},
  "data": {},
  "source": {}
}
console.log(Object.keys(yourobject).filter(x => x.includes('datasource')).length);

答案 1 :(得分:1)

var a = {
"datasource1":{},
"datasource2":{},
"datasource3":{},
"datasource5":{},
"datasource4":{},
"data":{},
"source":{}
}
for(var key in a){
  if(key.indexOf('datasource') > -1){ // or ==0 if "starts with"
    console.log('I have datasource');
  }
}