How to perform wildcard key search in JSON using Javascript?

Viewed 51

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
1 Answers

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

const findProp = (json, prop, wildcard) =>
  Object.values(json)
  .flatMap(person => Object.entries(person)
    .filter(([key, value]) => wildcard ? key.includes(prop) : key === prop)
    .map(([key, value]) => ({
      [key]: value
    }))
  )

console.log(findProp(json, prop1, false))
console.log(findProp(json, prop2, true))

const findProp2 = (json, prop, wildcard) =>
  Object.values(json)
  .flatMap(person => Object.entries(person)
    .filter(([key, value]) => wildcard ? key.includes(prop) : key === prop)
  ).reduce((acc, [key, value]) => {
    acc[key] = value
    return acc
  }, {})


console.log(findProp2(json, prop1, false))
console.log(findProp2(json, prop2, true))

Related