Skip to content

Instantly share code, notes, and snippets.

@austinmao
Last active August 29, 2015 14:25
Show Gist options
  • Save austinmao/ab325ff8475bcbb978a2 to your computer and use it in GitHub Desktop.
Save austinmao/ab325ff8475bcbb978a2 to your computer and use it in GitHub Desktop.
Finds the value at key of a nested object using lodash
// here is the nested object to do the find on
{
"level1": {
"level2": {
"level3": {
"level4": {
"level5": "value"
}
}
}
}
}
// you can pass this and it will return "value"
{
"level4": {
"level5": "value"
}
}
// you can pass this and it will return null
{
"level4": {
"level5": "not the right value"
}
}
// you can pass this and it will return null
{
"level4": {
"notRightKey": "blah"
}
}
import _ from 'lodash'
import flatten from 'flat' // flatten nested object
import _s from 'underscore.string'
class Validate {
/**
* test to see if a key value pair is present in a [potentially] nested object
* @param {object} obj [nested object]
* @param {object} key [nested object representing the unique key]
* @param {value} val [any value to test for]
* @example
* // here is the nested object to do the find on
{
"level1": {
"level2": {
"level2a": "nesting",
"level2b": "nesting again",
"level3": {
"level4": {
"level5": "value"
}
}
}
}
}
// you can pass this and it will return "value"
{
"level4": {
"level5": "value"
}
}
// you can pass this and it will return null
{
"level4": {
"level5": "not the right value"
}
}
// you can pass this and it will return null
{
"level4": {
"notRightKey": "value"
}
}
* @return {Boolean} [whether the key-value pair exists]
*/
hasKeyValuePair(findObj) {
// flatten nested object and key
const flatObj = flatten(this.obj)
const flatFindObj = flatten(findObj)
// create array of keys
const objKeys = Object.keys(flatObj)
const findObjKeys = Object.keys(flatFindObj)
// find where key is in nested obj
const keyTree = _(objKeys).find(nestedKey => {
// return the nestedKey string that includes key
return (_s.include(nestedKey, findObjKeys))
})
// return if no keyTree found
if (!keyTree || is.empty(keyTree)) return false
// find the value of the key
const keyVal = _(this.obj).get(keyTree)
const findVal = _(findObj).get(findObjKeys[0])
// return true if values are equal
return (keyVal === findVal)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment