Reputation: 51
Hey so I have a JSON string:
{
"cmd.test1":"test1",
"cmd.test2":"test2",
"ab.test1":"nthing"
}
and I want to get all keys (in this case it's cmd.test1 or cmd.test2) starting with a prefix of "cmd.". I am unable to get what I should do. Can someone help me? Thanks!
Upvotes: 3
Views: 3775
Reputation: 41893
Possible solution using Object.keys
and Array#filter
.
RegExp
solutionvar obj = {
"cmd.test1":"test1",
"cmd.test2":"test2",
"ab.test1":"nthing"
},
res = Object.keys(obj).filter(v => /^cmd/.test(v));
console.log(res);
String#startsWith
solutionvar obj = {
"cmd.test1":"test1",
"cmd.test2":"test2",
"ab.test1":"nthing"
},
res = Object.keys(obj).filter(v => v.startsWith('cmd'));
console.log(res);
Upvotes: 7