dotpath-strict

Get or set property value by dotpath string, throws on failure.

Usage no npm install needed!

<script type="module">
  import dotpathStrict from 'https://cdn.skypack.dev/dotpath-strict';
</script>

README

node-dotpath-strict

NPM Package Build Status Coverage Status Dependency Status

Aren't there a million of these already?

I couldn't find one that distinguishes between a property that is unset and one that is set to undefined so I made this. It throws an error when attempting to access a nonexisting property. Supports basic dot notation and numeric brackets.

Example

var dotPath = require("dotpath-strict");
var post = { title: "Readme", author: { firstName: "Hugh", lastName: "Mungus" } };
dotPath(post, "author.firstName");
//"Hugh"

Installation

npm i dotpath-strict

API Reference

dotPath(object, path, [value]) ⇒ *

Kind: Exported function
Throws:

  • ReferenceError
  • TypeError

Params

  • object Object
  • path string
  • [value] string - Set property to this value

Example

var obj = { a: { aa: 1, ab: [ "1", "2" ] }, b: undefined, c: null };
dotPath(obj, "a.aa");
//1
dotPath(obj, "a.ab[1]");
//"2"
dotPath(obj, "b");
//undefined
dotPath(obj, "c");
//null
dotPath(obj, "d");
//ReferenceError: d is not defined
dotPath(obj, "d", "2");
//"2"
dotPath(obj, "d.e", 3);
//TypeError: d is not an object
dotPath(obj, "d", { e: 3 });
//{ e: 3 }
dotPath(obj, "d.e");
//3

License

MPL 2.0