Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform wildcard key search in JSON using Javascript?

How to perform key search in JSON?
I want to get all matching string keys from the JSON, not the values.

let json = {
    "first": {
        "first_fullname": 'abc',
        "first_address": '1 street name',
        "first_phone": 123456
    },
    "second": {
        "second_fullname": 'xyz',
        "second_address": '2 street name',
        "second_phone": 987654    
    }
}


var prop1 = 'first_address'
var prop2 = 'address'

Object.keys(json).forEach((person) => { 
    Object.keys(json[person]).forEach((attr) => { 
        if (prop1 in json[person]) {
            console.log(prop1)
        }
    })
});

Object.keys(json).forEach((person) => { 
    Object.keys(json[person]).forEach((attr) => { 
        if (prop2 in json[person]) {
            console.log(prop2)
        }
    })
});

Expecting all key strings containing *address*, with use of wildcard.

first_address
second_address

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would write this as a function which takes the property and a wildcard flag, and then filter the keys of each person to find ones which match the property, using strict equality for no wildcard or String.includes for wildcards:

let json = {
  "first": {
    "first_fullname": 'abc',
    "first_address": '1 street name',
    "first_phone": 123456
  },
  "second": {
    "second_fullname": 'xyz',
    "second_address": '2 street name',
    "second_phone": 987654
  }
}


var prop1 = 'first_address'
var prop2 = 'address'

const hasProp = (json, prop, wildcard) =>
  Object.values(json)
  .flatMap(person => Object.keys(person)
    .filter(key => wildcard ? key.includes(prop) : key === prop)
  )
  
console.log(hasProp(json, prop1, false))
console.log(hasProp(json, prop2, true))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading