data_object-to-attributes.js

/**
 * @module objectToAttributes
 * @description Takes an object and "spreads" it as html attributes similar to what JSX does.
 *
 * @since 1.2.15
 *
 * @param {object} props The object to spread.
 *
 * @return {string} The html attributes.
 *
 * @example
 * import { objectToAttributes } from "@gravityforms/utils";
 *
 * function Example() {
 *   const customAttributes = {
 *      'placeholder': 'placeholder text',
 *      'name': 'idForThing',
 *   },
 * 	 const customClasses = [
 * 	    'class-one',
 * 	    'class-two',
 * 	 ],
 *   const props = {
 * 		class: [
 * 			'class-required',
 * 			...customClasses,
 * 		],
 * 		id: 'idForThing',
 * 		...customAttributes,
 *   };
 *   objectToAttributes( props );
 * }
 *
 */
export default function objectToAttributes( props ) {
	const htmlAttributes = [];
	Object.entries( props ).forEach( ( [ key, value ] ) => {
		// Confirm the attribute either has a value or it's an intentional null alt tag
		if ( value.length || key === 'alt' ) {
			// Handling of classes
			if ( Array.isArray( value ) ) {
				// Clean up any null class names
				const cleanValues = value.filter( ( v ) => v );
				htmlAttributes.push( `${ key }="${ cleanValues.join( ' ' ) }"` );
			} else {
				htmlAttributes.push( `${ key }="${ value }"` );
			}
		}
	} );
	return htmlAttributes.join( ' ' );
}