BarryBones41 BarryBones41 - 3 months ago 7
Javascript Question

Create an object based on file path string

Given the path "documents/settings/user"

How can this be made into a nested object

Result

{
documents : {
settings : {
user : {}
}
}
}


I can't think of how to reference each previous path

var dir = {};

var paths = "documents/settings/user".split('/')
for (var i = 0; i < paths.length; i++) {
var path = paths[i];
if(i === 0)
dir[path] = {};
//else
//dir[path[i-?]] = {};
}

Answer

This is actually done quite easily with .reduce().

var dir = {}

var paths = "documents/settings/user".split('/')

paths.reduce(function(dir, path) {
  return dir[path] = {}
}, dir)

console.log(dir)

Because the first parameter is always the last value returned (or the first value provided), all we need to do is return the object being assigned to the current path. And because an assignment results in the value being assigned, we can use that as the expression of the return statement itself.


If needed, you can guard against empty path names due to adjacent separators.

var dir = {}

var paths = "documents///settings/user".split('/')

paths.reduce(function(dir, path) {
  return path ? (dir[path] = {}) : dir
}, dir)

console.log(dir)

Comments