deep_get.js (2562B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var isObjectLike = require( '@stdlib/assert/is-object-like' ); 24 var isString = require( '@stdlib/assert/is-string' ).isPrimitive; 25 var isArray = require( '@stdlib/assert/is-array' ); 26 var copy = require( './../../copy' ); 27 var validate = require( './validate.js' ); 28 var defaults = require( './defaults.json' ); 29 var dget = require( './dget.js' ); 30 31 32 // MAIN // 33 34 /** 35 * Returns a nested property value. 36 * 37 * @param {ObjectLike} obj - input object 38 * @param {(string|Array)} path - key path 39 * @param {Options} [options] - function options 40 * @param {string} [options.sep='.'] - key path separator 41 * @throws {TypeError} second argument must be a string primitive or key array 42 * @throws {TypeError} options argument must be an object 43 * @throws {TypeError} must provide valid options 44 * @returns {*} nested property value 45 * 46 * @example 47 * var obj = { 'a': { 'b': { 'c': 'd' } } }; 48 * var val = deepGet( obj, 'a.b.c' ); 49 * // returns 'd' 50 * 51 * @example 52 * var arr = [ 53 * { 'a': [ {'x': 5} ] }, 54 * { 'a': [ {'x': 10} ] } 55 * ]; 56 * var val = deepGet( arr, '1.a.0.x' ); 57 * // returns 10 58 * 59 * @example 60 * var obj = { 'a': { 'b': { 'c': 'd' } } }; 61 * var val = deepGet( obj, ['a','b','c'] ); 62 * // returns 'd' 63 * 64 * @example 65 * var obj = { 'a': { 'b': { 'c': 'd' } } }; 66 * var val = deepGet( obj, 'a/b/c', { 67 * 'sep': '/' 68 * }); 69 * // returns 'd' 70 */ 71 function deepGet( obj, path, options ) { 72 var isStr; 73 var props; 74 var opts; 75 var err; 76 if ( !isObjectLike( obj ) ) { 77 return; 78 } 79 isStr = isString( path ); 80 if ( !isStr && !isArray( path ) ) { 81 throw new TypeError( 'invalid argument. Key path must be a string primitive or a key array. Value: `' + path + '`.' ); 82 } 83 opts = copy( defaults ); 84 if ( arguments.length > 2 ) { 85 err = validate( opts, options ); 86 if ( err ) { 87 throw err; 88 } 89 } 90 if ( isStr ) { 91 props = path.split( opts.sep ); 92 } else { 93 props = path; 94 } 95 return dget( obj, props ); 96 } 97 98 99 // EXPORTS // 100 101 module.exports = deepGet;