1.0.2 ⢠Published 4 years ago
getref v1.0.2
š¤ 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 thepath
. - 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"