PluginProbe ʕ •ᴥ•ʔ
AlphaListing / 4.4.0
AlphaListing v4.4.0
trunk 4.3.4 4.3.5 4.3.6 4.3.7 4.4.0
alphalisting / scripts / components / utils / terms.js
alphalisting / scripts / components / utils Last commit date
terms.js 1 month ago
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