1.1.4 • Published 4 years ago

get-deep-value v1.1.4

Weekly downloads
6
License
MIT
Repository
github
Last release
4 years ago

get-deep-value

This is a simple Javascript utility which will quickly and safely retrieve a value from a nested array and/or object.

Installation

First, use npm (or yarn) to install:

npm install get-deep-value

Then simply import the default function:

import getDeepValue from 'get-deep-value'

Use

getDeepValue takes three arguments:

ArgumentTypeDescription
baseobject or arrayThis is the object you want to traverse
pathstringThis describes the traversal path
fallbackanyoptional This is the value to return if traversal fails; default is null

Examples

We'll use this object for the base of all of the below examples:

const base = {
    my: {
        object: {
            value: 'foo'
        },
        array: [
            {
                value: 'bar'
            }
        ]
    }
}

You can access a nested object value:

getDeepValue(base, 'my.object.value')               // foo

Or a nested array value:

getDeepValue(base, 'my.array[0].value')             // bar

You can also use a dynamic path:

const typeName = 'object'
const arrayItem = 0

getDeepValue(base, `my.${typeName}.value`)          // foo
getDeepValue(base, `my.array[${arrayItem}].value`)  // bar

All of these will safely return null:

getDeepValue(base, 'no.object.value')               // null
getDeepValue(base, 'my.nonexistant.value')          // null
getDeepValue(base, 'my.object.nothing')             // null
getDeepValue(base, 'my.array[1].value')             // null

Optionally, you can specify a fallback value other than null:

getDeepValue(base, 'no.object.value', 'baz')        // baz
1.1.4

4 years ago

1.1.3

4 years ago

1.1.2

4 years ago

1.1.1

4 years ago

1.1.0

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago