5
\$\begingroup\$

I have the following data structure that's obtained from a third party:

var data = [
 ["Parent1", "Parent1.1", "Parent1.1.1"],
 ["Parent2", "Parent2.1", "Parent2.1.1"],
 ["Parent3", "Parent3.1", "Parent3.1.1"],
 ["Parent1", "Parent1.2", "Parent1.2.1"],
 ["Parent1", "Parent1.2", "Parent1.2.2"]
];

Where child nodes may or may not be present.
I'm turning it into a tree to represent the data logically:

var tree = {
 "Parent1": {
 "Parent1.1": ["Parent1.1.1"],
 "Parent1.2": ["Parent1.2.1", "Parent1.2.2"]
 },
 "Parent2": {
 "Parent2.1": ["Parent2.1.1"]
 },
 "Parent3": {
 "Parent3.1": ["Parent3.1.1"]
 }
};

What I'm currently doing seems rather straightforward to myself, but somewhat convoluted due to the numerous return statements:

var tree = data.reduce(function(tree, item) {
 if (!item[0]) return tree;
 tree[item[0]] = tree[item[0]] || {};
 if (!item[1]) return tree;
 tree[item[0]][item[1]] = tree[item[0]][item[1]] || [];
 if (!item[2]) return tree;
 tree[item[0]][item[1]].push(item[2]);
 return tree;
}, {}); //Returns as shown above

Is there a better way to approach this problem, what improvements could be made?
The depth of the data is always fixed at three.

asked Sep 16, 2015 at 16:00
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

I was also facing similar issue where I needed to convert the 2-D array to a tree structure. This code might help.:)

var tree = data.reduce(function(tree, item) {
 var tempTree = tree;
 for(var i=0;i<item.length;i++){
 if(!tempTree[item[i]])
 tempTree[item[i]] = {};
 tempTree = tempTree[item[i]];
 }
 return tree;
}, {});
Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
answered Jan 18, 2018 at 16:43
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.