Last active
April 25, 2020 16:53
-
-
Save sirdarthvader/17b183872ba961a1673da2aea59af4f9 to your computer and use it in GitHub Desktop.
A javascript function to get string of array and return a tree of data
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
/** | |
* | |
* @param {Array} arr of strings provided for each Prodct listing / search page by aloglia | |
* @returns {Array} Modified array of nested objects in a tree structure for each category | |
*/ | |
export const getTreeData = arr => { | |
let mapper = {} | |
let root = { | |
children: [] | |
} | |
/** | |
* Map over incoming array of string and create parent child tree structure for each provided category | |
*/ | |
for (const str of arr) { | |
let splits = str.split('>'), | |
path = '' | |
splits.reduce((parent, id, i) => { | |
//preserve the original filter key for algolia | |
i === splits.length - 1 ? (path += `${id}`) : (path += `${id}>`) | |
if (!mapper[path]) { | |
let name = id | |
name = name.trim() // clean any kind of white space as a result of split in the previous step | |
const obj = { | |
id: id, | |
label: name, | |
value: path | |
} | |
mapper[path] = obj // set the new object with unique path | |
parent.children = parent.children || [] //set to empty array in case child not applicable | |
parent.children.push(obj) | |
} | |
return mapper[path] | |
}, root) | |
} | |
return root.children | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment