0

I am trying to make something that takes arrays of strings, and then builds chains of nested objects that basically store what strings come after what in the input arrays. Initially, these chains had depths of 2, but I need to be able to generate higher-depth chains.

Basically, I need to take an array like this:

["test1", "test2", "test3", "test4"]

and convert it into this:

{
    "test1":
    {
        "test2":
        {
            "test3":
            {
                "test4": {}
            }
        }
    }
}
0

2 Answers 2

6

This looks like a job for Array#reduce:

function objectFromPath (path) {
  var result = {}
  
  path.reduce(function (o, k) {
    return (o[k] = {})
  }, result)
  
  return result
}

var path = ["test1", "test2", "test3", "test4"]

console.log(objectFromPath(path))
.as-console-wrapper { min-height: 100%; }

Sign up to request clarification or add additional context in comments.

2 Comments

Don't think he's gonna get any better than this
Thank you for the answer, and especially for editing the title of my question. Now I actually know what what I was trying to do is called!
1

I wanted to solve a similar problem, but I wanted to set a value at the end of the path within the resulting object, and I wanted to provide an initial object. I started with gyre's function and added some extra magic to satisfy my use case.

// Creates a nested object from an array representing the path of keys
//
// Takes 2 optional arguments:
//     - a value to set at the end of the path
//     - an initial object
// 
// Ex: let house = objectFromPath(['kitchen', 'fridge'], 'empty', {civic: 123})
//     => house = {civic: 123, kitchen: {fridge: 'empty'}}
const objectFromPath = (path, value = {}, obj = {}) =>
{
    path.reduce((result, key, i, source) =>
        {
            if(i === (source.length - 1))
            {
                return (result[key] = value)
            }
            else
            {
                return (result[key] = {})
            }
        },
        obj
    )
    
    return obj;
}


// Demo: house = {civic: 123, kitchen: {fridge: 'empty'}}
console.log(
  objectFromPath(
    ['kitchen', 'fridge'],
    'empty',
    {civic: 123}
  )
)

Comments

Your Answer

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.