terms.js
41 lines
| 1 | /** |
| 2 | * External dependencies |
| 3 | */ |
| 4 | import { groupBy } from 'lodash'; |
| 5 | |
| 6 | /** |
| 7 | * Returns terms in a tree form. |
| 8 | * |
| 9 | * @param {Array} flatTerms Array of terms in flat format. |
| 10 | * |
| 11 | * @return {Array} Array of terms in tree format. |
| 12 | */ |
| 13 | export function buildTermsTree( flatTerms ) { |
| 14 | const flatTermsWithParentAndChildren = flatTerms.map( ( term ) => { |
| 15 | return { |
| 16 | children: [], |
| 17 | parent: null, |
| 18 | ...term, |
| 19 | }; |
| 20 | } ); |
| 21 | |
| 22 | const termsByParent = groupBy( flatTermsWithParentAndChildren, 'parent' ); |
| 23 | if ( termsByParent.null && termsByParent.null.length ) { |
| 24 | return flatTermsWithParentAndChildren; |
| 25 | } |
| 26 | const fillWithChildren = ( terms ) => { |
| 27 | return terms.map( ( term ) => { |
| 28 | const children = termsByParent[ term.id ]; |
| 29 | return { |
| 30 | ...term, |
| 31 | children: |
| 32 | children && children.length |
| 33 | ? fillWithChildren( children ) |
| 34 | : [], |
| 35 | }; |
| 36 | } ); |
| 37 | }; |
| 38 | |
| 39 | return fillWithChildren( termsByParent[ '0' ] || [] ); |
| 40 | } |
| 41 |