Last active
November 18, 2021 22:08
-
-
Save psandeepunni/80f5a62f0540b7989729 to your computer and use it in GitHub Desktop.
Javascript function to flatten a nested Associative Array (tree) to a List
This file contains hidden or 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
var bfs = function(tree, key, collection) { | |
if (!tree[key] || tree[key].length === 0) return; | |
for (var i=0; i < tree[key].length; i++) { | |
var child = tree[key][i] | |
collection[child.id] = child; | |
bfs(child, key, collection); | |
} | |
return; | |
} | |
// Sample Usage | |
var flattenedCollection = {}; | |
var dataTree = {"children" : [ | |
{"id" : "1", "name" : "A", "children" : [{"id" : 11, "name" : "AA"},{"id" : 12, "name" : "AB"}]}, | |
{"id" : "2", "name" : "B", "children" : [{"id" : 21, "name" : "BA", "children" : [{"id":"211","name":"BAC"}]},{"id" : 22, "name" : "BB"}]}, | |
]}; | |
bfs(dataTree, "children", flattenedCollection); | |
console.log(flattenedCollection["211"].name); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Incase if someone wants just the leaf nodes,
var mockData = [];