recurse.js (1794B)
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 objectKeys = require( './../../keys' ); 24 var isPlainObject = require( '@stdlib/assert/is-plain-object' ); 25 var isArray = require( '@stdlib/assert/is-array' ); 26 27 28 // MAIN // 29 30 /** 31 * Recursively flattens an object. 32 * 33 * @private 34 * @param {Object} out - output object 35 * @param {ObjectLike} obj - input object 36 * @param {string} prefix - key prefix 37 * @param {NonNegativeInteger} depth - recursion depth 38 * @param {Options} opts - options 39 * @param {boolean} opts.flattenArrays - boolean indicating whether to flatten arrays 40 * @param {string} opts.delimiter - key path delimiter 41 * @returns {Object} output object 42 */ 43 function recurse( out, obj, prefix, depth, opts ) { 44 var keys; 45 var val; 46 var key; 47 var i; 48 if ( prefix ) { 49 prefix += opts.delimiter; 50 } 51 keys = objectKeys( obj ); 52 for ( i = 0; i < keys.length; i++ ) { 53 val = obj[ keys[i] ]; 54 key = prefix + keys[ i ]; 55 if ( depth ) { 56 if ( 57 (isPlainObject( val ) && objectKeys( val ).length) || 58 (opts.flattenArrays && isArray( val )) 59 ) { 60 recurse( out, val, key, depth-1, opts ); 61 continue; 62 } 63 } 64 out[ key ] = val; 65 } 66 return out; 67 } 68 69 70 // EXPORTS // 71 72 module.exports = recurse;