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

In my case, I need to fetch number of object whose keys have datasource keyword.

Biffen
  • 6,249
  • 6
  • 28
  • 36
T Sooraj
  • 556
  • 1
  • 5
  • 18

2 Answers2

2

You can use ES6 version.

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

ES5

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

If you want to check the keys starts with the term use x.startsWith('datasource') or x.indexOf("datasource")==0.

var yourobject = {
  "datasource1": {},
  "datasource2": {},
  "datasource3": {},
  "datasource5": {},
  "datasource4": {},
  "data": {},
  "source": {}
}
console.log(Object.keys(yourobject).filter(x => x.includes('datasource')).length);
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • indexOf won't work because keyword can occur anywhere in the key. He did not mention that keyword should be at the start of key string. – Piyush Beli Jan 17 '17 at 09:51
  • I will elaborate: Or `indexOf("datasource")==0` if you are looking for keys starting with datasource - This is likely the case since his key started with datasource and he did not specify "contain" but "have" – mplungjan Jan 17 '17 at 09:53
  • @mplungjan, Agreed in this case I prefer [`startsWith()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) – Satpal Jan 17 '17 at 09:54
  • Even better since you are using ES6 anyway. I stand corrected – mplungjan Jan 17 '17 at 09:56
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');
  }
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Adam Azad
  • 11,171
  • 5
  • 29
  • 70