crotoan crotoan - 11 months ago 69
Javascript Question

ES6 / lodash - check nested Object values with startsWith

is there any function or any fast way to check if some value in our object startsWith e.g asd


let obj = {
'child' : {
'child_key': 'asdfghhj'
'free': 'notasd',
'with': 'asdhaheg'

// check here if our obj has value that startsWith('asd')


Answer Source

You can recursively iterate object properties and check if property starts with prefix using find function:

function hasPropertyStartingWith(obj, prefix) {
  return !!Object.keys(obj).find(key => {
    if (typeof obj[key] === 'object') {
      return hasPropertyStartingWith(obj[key], prefix)
    if (typeof obj[key] === 'string') {
      return obj[key].startsWith(prefix)
    return false

console.log(hasPropertyStartingWith(obj, 'asd'))