0

Say I have this string/array: 'users.data.object.email' / [users, data, object, email]

How can I convert this string/array to a javascript object?

For example from the above string/array, the object would look like so:

{user: {
  data: {
    object: {
      email: {}
    }
  }
}
John Zenith
  • 472
  • 5
  • 10

1 Answers1

0

Using a recursive function and object reference, I was able to create the object structure:

/**
 * Create object from props
 * @param (string) prop The chainable properties. For example: 'user.posts.title'
 * @returns {Object} The created object from given props
 */
const createObjectFromProps = (prop) => {
    const objRef = {},
        keys = prop.split('.'),
        firstKey = keys[0];
    
    const createObjectProps =  (target = {}) => {
        const key = keys.shift();
        target[key] = {};
        
        // Track object prop
        objRef[key] = target;
        
        if (!keys.length) {
            return objRef[firstKey];
        }
    
        return createObjectProps(target[key]);
    };

    return createObjectProps();
};

const prop = 'user.data.object.email';

const obj = createObjectFromProps(prop);

console.log(obj);
John Zenith
  • 472
  • 5
  • 10