Skip to content

Instantly share code, notes, and snippets.

@sirdarthvader
Last active April 25, 2020 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sirdarthvader/17b183872ba961a1673da2aea59af4f9 to your computer and use it in GitHub Desktop.
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
/**
*
* @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