I have an object, and I’d like to get each "branch" of the "tree" as an array. (Feel free to correct my terminology also!) What I have is like the following:
var features = {
"f": {
"t": "100",
"f": {
"i": ['150'],
"b": ['300'],
"f": {
"k": 100
}
},
"l": ['255']
},
"c": {
"s": {
"t": ["100"]
},
"t": "100"
}
};
And I’d like to parse it into the following result, so I can iterate over it again and pass it into another function.
var result = [
"ffi",
"fffk",
"fl",
"ct"
]
What I have so far is on JS Bin here. Any help or pointers in the right direction would be greatly appreciated! Thanks!
asked May 28, 2014 at 19:06
kennethormandy
2,16014 silver badges16 bronze badges
-
possible duplicate of Flatten object to array?Etheryte– Etheryte2014年05月28日 19:17:04 +00:00Commented May 28, 2014 at 19:17
-
@Nit I don’t think so, I am just looking for the keys, in a way that retains the entire branch. I appreciate the link, though, it might still be helpful for getting to the end result.kennethormandy– kennethormandy2014年05月28日 22:47:31 +00:00Commented May 28, 2014 at 22:47
1 Answer 1
You can try my un-flatten-tree npm module to convert the tree into the list of branches. Also note that 'map' from lodash is used for object traversal.
function walk(tree) {
return _.map(tree, function (v, k) {
return {
name: k,
items: (typeof v !== 'object' || v instanceof Array) ? [] : walk(v)
};
});
}
function getChildNodes(node) {
return node.items.map(function (item) {
return {
name: node.name + item.name,
items: item.items
};
});
}
var result = uft.flatten(walk(features), getChildNodes)
.filter(function (node) { return node.items.length === 0; })
.map(function (node) { return node.name; });
Live example:
Sign up to request clarification or add additional context in comments.
Comments
lang-js