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