1.0.2 • Published 4 years ago

getref v1.0.2

Weekly downloads
-
License
ISC
Repository
github
Last release
4 years ago

install size

šŸ¤ Safely get the reference of a nested property from an object.

  • šŸš€ Lightweight.
  • āšŖļø Zero dependencies.

Table of contents

Import

const getref = require("getref");

Usage

const [ref, lastKey] = getRef(object, path);
  • object object: Target object.
  • path string | Array<string>: Dot path route "prop1.prop2" or array route ["prop1", "prop2"].

Returns [ref, lastKey]:

  • ref object: Reference of the parent of the last key of the path.
  • lastKey string: Last key of the path.

Why return ref, lastKey?

You can access dynamically without any danger to a deep nested property.

let bike = {
	wheel1: {
		type: "AD-56",
		status: "ok"
	},
	wheel2: {
		type: "AT-77",
		status: "ok"
	},
};

Editing:

let [ref, lastKey] = getRef(bike, "wheel2.type");
ref[lastKey] = "newType";

Creating new nested property:

let [ref, lastKey] = getRef(bike, "wheel2.dontExists.abc.qwe");
ref[lastKey] = "nowItExists";

Deleting:

let [ref, lastKey] = getRef(bike, "wheel2.type");
delete ref[lastKey];

Safe selecting:

let [ref, lastKey] = getRef(bike, "wheel2.type.dontExists.asd.qwe");
if (! ref[lastKey]) {
	console.log("That property doesn't exists");
};

Example

let bike = {
	wheel1: {
		type: "AD-56",
		status: "ok"
	},
	wheel2: {
		type: "AT-77",
		status: "ok"
	},
};

let [ref, lastKey] = getRef(bike, "wheel2.type"); // or getRef(bike, ["wheel2", "type"])
const wheel2_type = ref[lastKey]; // "AT-77"

Go to top

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago