S
S
superivankorolev2016-10-07 05:29:52
JavaScript
superivankorolev, 2016-10-07 05:29:52

How to create intermediate objects from an object?

Suppose there is:
routes\jsdom\node_modules\array-equal
routes\jsdom\node_modules\asn1
routes\jsdom\node_modules\assert-plus
routes\jsdom\node_modules\async
routes\jsdom\node_modules\ansi-styles
routes\jsdom\node_modules\ aws4
routes={};
I want to get a function

function add_routes(patch){


}

which outputs nested objects
routes.jsdom.node_modules.array-equal
routes.jsdom.node_modules.asn1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Александр Коротаев, 2016-10-07
@superivankorolev

Array.reduce поможет

var root = {};
function add_routes(path, root) {
  path.split('\\')
    .reduce(function(currentNode, item){
      return currentNode = currentNode[item] = {};
    }, root)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question