123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- 'use strict';
- var isObj = require('is-obj');
-
- module.exports.get = function (obj, path) {
- if (!isObj(obj) || typeof path !== 'string') {
- return obj;
- }
-
- var pathArr = getPathSegments(path);
-
- for (var i = 0; i < pathArr.length; i++) {
- var descriptor = Object.getOwnPropertyDescriptor(obj, pathArr[i]) || Object.getOwnPropertyDescriptor(Object.prototype, pathArr[i]);
- if (descriptor && !descriptor.enumerable) {
- return;
- }
-
- obj = obj[pathArr[i]];
-
- if (obj === undefined || obj === null) {
- // `obj` is either `undefined` or `null` so we want to stop the loop, and
- // if this is not the last bit of the path, and
- // if it did't return `undefined`
- // it would return `null` if `obj` is `null`
- // but we want `get({foo: null}, 'foo.bar')` to equal `undefined` not `null`
- if (i !== pathArr.length - 1) {
- return undefined;
- }
-
- break;
- }
- }
-
- return obj;
- };
-
- module.exports.set = function (obj, path, value) {
- if (!isObj(obj) || typeof path !== 'string') {
- return;
- }
-
- var pathArr = getPathSegments(path);
-
- for (var i = 0; i < pathArr.length; i++) {
- var p = pathArr[i];
-
- if (!isObj(obj[p])) {
- obj[p] = {};
- }
-
- if (i === pathArr.length - 1) {
- obj[p] = value;
- }
-
- obj = obj[p];
- }
- };
-
- module.exports.delete = function (obj, path) {
- if (!isObj(obj) || typeof path !== 'string') {
- return;
- }
-
- var pathArr = getPathSegments(path);
-
- for (var i = 0; i < pathArr.length; i++) {
- var p = pathArr[i];
-
- if (i === pathArr.length - 1) {
- delete obj[p];
- return;
- }
-
- obj = obj[p];
- }
- };
-
- module.exports.has = function (obj, path) {
- if (!isObj(obj) || typeof path !== 'string') {
- return false;
- }
-
- var pathArr = getPathSegments(path);
-
- for (var i = 0; i < pathArr.length; i++) {
- obj = obj[pathArr[i]];
-
- if (obj === undefined) {
- return false;
- }
- }
-
- return true;
- };
-
- function getPathSegments(path) {
- var pathArr = path.split('.');
- var parts = [];
-
- for (var i = 0; i < pathArr.length; i++) {
- var p = pathArr[i];
-
- while (p[p.length - 1] === '\\' && pathArr[i + 1] !== undefined) {
- p = p.slice(0, -1) + '.';
- p += pathArr[++i];
- }
-
- parts.push(p);
- }
-
- return parts;
- }
|