Multiple arrays into JavaScript object
You could save the last value for later using this value as key for an empty string and the rest for creating a nested object.
let arrays = [['helpers', 'ConfigHelper.java'], ['helpers', 'GenerateRandomString.java'], ['helpers', 'package-info.java'], ['helpers', 'ScreenshotHelper.java'], ['pages', 'LoginPage.java'], ['pages', 'package-info.java'], ['pages', 'tests', 'LoginPageTest.java'], ['pages', 'tests', 'package-info.java'], ['pages', 'util', 'package-info.java'], ['pages', 'util', 'PageObject.java'], ['pages', 'util', 'PageObjectTest.java'], ['pages', 'util', 'PrimaryMethods.java'], ['webDriverSetup', 'browserDriverFactories', 'ChromeDriverFactory.java']],
treeView = arrays.reduce((tree, [...array]) => {
var last = array.pop();
array.reduce((o, k) => o[k] = o[k] || {}, tree)[last] = '';
return tree;
}, {});
console.log(treeView);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just check if the object key already exits.
let treeView = {};
arrays.forEach(array => {
array.reduce(function(o, key) {
if (!treeView[key]) {
return (o[key] = {});
} else {
return (o[key] = treeView[key]);
}
}, treeView);
});
console.log(treeView);