1.1.1 • Published 6 years ago

safely-nested v1.1.1

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

safely-nested Build Status

A safe way to access values in deeply nested objects.

Installation

npm install safely-nested

Syntax

safely-nested(path, object[, fallback])

Parameters

path
  a string such as    "foo.bar.baz"
  or an array such as ["foo", "bar", "baz"]

object
  any javascript object

fallback (optional, defaults to undefined)
  whatever you wish to return in case of failure

Return value

The nested value or fallback.

Usage

var safe = require("safely-nested");

var nest = {
  foo: {
    bar: {
      baz: 1,
      qux: ["quux", "corge"]
    }
  }
};

var invalidPath = "foo.bar.qux.2";
var fallback = "grault";

safe("foo.bar.baz", nest); // 1
safe("foo.bar.qux.0", nest); // 'quux'
safe(invalidPath, nest); // undefined
safe(invalidPath, nest, fallback); // 'grault'

// you can also pass in a callback
var callback = function() {
  console.log('nothing here!');
  return "grault";
};

safe(invalidPath, nest, callback) // [Function: callback]
safe(invalidPath, nest, callback()) // grault

// or pass one inline
safe(
  invalidPath,
  nest,
  (function() {
    console.log("nothing here!");
    return "grault";
  })()
)
1.1.1

6 years ago

1.1.0

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago