flatten_object.js (2053B)
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 copy = require( './../../copy' ); 25 var defaults = require( './defaults.js' ); 26 var validate = require( './validate.js' ); 27 var flatten = require( './flatten.js' ); 28 29 30 // MAIN // 31 32 /** 33 * Flattens an object. 34 * 35 * @param {ObjectLike} obj - object to flatten 36 * @param {Options} [options] - function options 37 * @param {NonNegativeInteger} [options.depth] - maximum depth to flatten 38 * @param {boolean} [options.copy=false] - boolean indicating whether to deep copy 39 * @param {boolean} [options.flattenArrays=false] - boolean indicating whether to flatten arrays 40 * @param {string} [options.delimiter='.'] - key path delimiter 41 * @throws {TypeError} first argument must be object-like 42 * @throws {TypeError} options argument must be an object 43 * @throws {TypeError} must provide valid options 44 * @returns {ObjectLike} flattened object 45 * 46 * @example 47 * var obj = {'a':{'b':{'c':'d'}}}; 48 * 49 * var out = flattenObject( obj ); 50 * // returns {'a.b.c':'d'} 51 */ 52 function flattenObject( obj, options ) { 53 var opts; 54 var err; 55 if ( !isObjectLike( obj ) ) { 56 throw new TypeError( 'invalid argument. First argument must be object-like. Value: `' + obj + '`.' ); 57 } 58 opts = copy( defaults ); 59 if ( arguments.length > 1 ) { 60 err = validate( opts, options ); 61 if ( err ) { 62 throw err; 63 } 64 } 65 return flatten( obj, opts ); 66 } 67 68 69 // EXPORTS // 70 71 module.exports = flattenObject;