crotoan crotoan - 2 months ago 17
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

Example:

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

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


Regards

Answer

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