Javascript array for the object

I have an array that looks like this:

files = [ 'Dashboard/Logs/Errors', 'Dashboard/Logs/Other', 'Accounts/Main', ] 

I want to do this:

 navigation = [ { "title": "Dashboard", "dropdown": [ { "title": "Logs", "dropdown": [ { "title": "Errors", }, { "title": "Other", } ] } ] }, { "title": "Accounts", "dropdown": [ { "title": "Main", } ] } ] 

I have the following:

 var navigation = []; for (var i = 0; i < files.length; i++) { var parts = files[i].split('/'); navigation.push({title: parts[0]}); for (var j = 1; j < parts.length; j++) { } } 

I am having difficulty figuring out a decent way to do this. That I still don’t work, because it creates two objects under the navigation, each with title: "Dashboard" . Any ideas for a smart approach? Thanks:)

+7
javascript
source share
2 answers

This should lead to the desired result:

 var files = [ 'Dashboard/Logs/Errors', 'Dashboard/Logs/Other', 'Accounts/Main', ]; var navigation = []; // Iterates through a navigation array and returns the object with matching title, if one exists. var getNavigationObject = function(nav, title) { for (var i = 0; i < nav.length; i++) { if (nav[i].title == title) { return nav[i]; } } }; // Adds a file to the nav. // The input is an array of file components (ie file.split('/')) // This works by recursively adding each component of a file. var addToNav = function (nav, components) { var n = getNavigationObject(nav, components[0]); if (!n) { n = { title: components[0] }; nav.push(n); } if (components.length > 1) { n.dropdown = n.dropdown || []; addToNav(n.dropdown, components.slice(1)); } }; // Actually call `addToNav` on each file. files.forEach(function(e) { addToNav(navigation, e.split('/')); }); // Produces the result in string form. JSON.stringify(navigation, null, 2) 

This works by recursively checking if a given element matches the file component. If so, it is repeated in this β€œdrop down” component. Otherwise, he creates it.

+7
source share

This is an approach with a temporary object and some array methods without the overhead of searching.

 var files = ['Dashboard/Logs/Errors', 'Dashboard/Logs/Other', 'Accounts/Main'], navigation = function (data) { var r = [], o = {}; data.forEach(function (a) { var s = r; a.split('/').reduce(function (p, b) { if (p.children) { p.value.dropdown = p.value.dropdown || []; s = p.value.dropdown; p = p.children; } if (!(b in p)) { p[b] = { value: { title: b }, children: {} }; s.push(p[b].value); } return p[b]; }, o); }); return r; }(files); document.write('<pre>' + JSON.stringify(navigation, 0, 4) + '</pre>'); 
+1
source share

All Articles