Last active
June 25, 2021 11:26
-
-
Save varunrayen/a9a17f7aacb81823978249a61a0d8f97 to your computer and use it in GitHub Desktop.
Sorting a category list from a flat database for insert into a hierarchy-constrained one
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
module.exports = function sortCategoriesForInsert (inputJson) { | |
let dataTree = function (inputJson, root) { | |
var r = [], o = {}; | |
inputJson.forEach(function (a) { | |
o[a.id] = { data: a, children: o[a.id] && o[a.id].children }; | |
if (a.parent_id === root) { | |
r.push(o[a.id]); | |
} else { | |
o[a.parent_id] = o[a.parent_id] || {}; | |
o[a.parent_id].children = o[a.parent_id].children || []; | |
o[a.parent_id].children.push(o[a.id]); | |
} | |
}); | |
return r; | |
}(inputJson, null) | |
let sortedDataTree = dataTree.reduce(function traverse(r, a) { | |
return r.concat(a.data, (a.children || []).reduce(traverse, [])); | |
}, []) | |
return sortedDataTree | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment