Adi
Adi

Reputation: 51

Get every key starting with a prefix in Node.JS from JSON Data

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

Answers (1)

kind user
kind user

Reputation: 41893

Possible solution using Object.keys and Array#filter.

  • RegExp solution

var obj = {
    "cmd.test1":"test1",
    "cmd.test2":"test2",
    "ab.test1":"nthing"
}, 
res = Object.keys(obj).filter(v => /^cmd/.test(v));

console.log(res);

  • String#startsWith solution

var obj = {
    "cmd.test1":"test1",
    "cmd.test2":"test2",
    "ab.test1":"nthing"
}, 
res = Object.keys(obj).filter(v => v.startsWith('cmd'));

console.log(res);

Upvotes: 7

Related Questions