Home > Net >  How to perform wildcard key search in JSON using Javascript?
How to perform wildcard key search in JSON using Javascript?

Time:09-02

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

CodePudding user response:

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))

  • Related