data_find-nested-object.js

/**
 * @module findNestedObject
 * @description Finds a nested object in an object by searching for a property and value.
 *
 * @since 2.0.1
 *
 * @param {object} objToSearch  The object to search.
 * @param {string} propToSearch The property to search for.
 * @param {string} valueToMatch The value to match.
 *
 * @return {object | null}
 * @example
 * import { findNestedObject } from "@gravityforms/utils";
 *
 * const obj = {
 *  foo: {
 *  bar: {
 *  baz: 'hello',
 *  },
 *  },
 *  };
 *  const found = findNestedObject( obj, 'baz', 'hello' );
 *  console.log( found ); // { baz: 'hello' }
 *  const notFound = findNestedObject( obj, 'baz', 'goodbye' );
 *  console.log( notFound ); // null
 *
 */
export default function findNestedObject( objToSearch, propToSearch = '', valueToMatch = '' ) {
	const search = ( obj ) => {
		if ( typeof obj === 'object' ) {
			for ( const prop in obj ) {
				if ( Object.prototype.hasOwnProperty.call( obj, prop ) ) {
					if ( prop === propToSearch && obj[ prop ] === valueToMatch ) {
						return obj;
					}
					const found = search( obj[ prop ] );
					if ( found ) {
						return found;
					}
				}
			}
		}
		return null;
	};

	return search( objToSearch );
}