1

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!

2
  • possible duplicate of Flatten object to array? Commented 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. Commented May 28, 2014 at 22:47

1 Answer 1

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:

https://jsfiddle.net/iyegoroff/ut3bz6oc/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.