Last active
February 12, 2023 20:25
-
-
Save karpolan/03e2976ed9b9e2e6d9ea5bfc08114d92 to your computer and use it in GitHub Desktop.
React component to print out <ul> list with all properties of JavaScript object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMemo } from 'react'; | |
const sortByAbc = ([a], [b]) => a.localeCompare(b); | |
const sortByZxy = ([a], [b]) => b.localeCompare(a); | |
const sortNone = () => 0; | |
/** | |
* Renders <ul> list with all properties of the given JavaScript object | |
* @param {object} object - object to print out | |
* @param {boolean} [sortAbc] - properties sorted A-Z when true | |
* @param {boolean} [sortZxy] - properties sorted Z-A when true | |
*/ | |
export const ObjectAsList = ({ | |
className = '', | |
object = {}, | |
sortAbc = false, | |
sortZxy = false, | |
...restOfProps | |
}) => { | |
const objectPropsWithSorting = useMemo(() => { | |
const sortFunc = sortAbc ? sortByAbc : sortZxy ? sortByZxy : sortNone; | |
return Object.entries(object) | |
.sort(sortFunc) | |
.map(([key, value]) => | |
typeof value === 'object' ? ( | |
<li key={key} className="propertyAsObject"> | |
<span className="key title">{key}:</span> | |
<ObjectAsList object={value} {...{ sortAbc, sortZxy }} /> | |
</li> | |
) : ( | |
<li key={key}> | |
<span className="key title">{key}:</span>{' '} | |
<span className="value property">{String(value)}</span> | |
</li> | |
) | |
); | |
}, [object, sortAbc, sortZxy]); | |
return ( | |
<ul className={`objectAsList ${className}`} {...restOfProps}> | |
{objectPropsWithSorting} | |
</ul> | |
); | |
}; | |
export default ObjectAsList; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment