Create a object i an object based on the array of string value

san*_*osh 6 javascript node.js

I need to update the object name based on the array of the string value and the last string value should be an array.

I use array.forEach loop but I don't know how to find the object inside an object if it exists and the myArray contain around 10,000 strings.

const myArray = [
  '/unit/unit/225/unit-225.pdf',
  '/nit/nit-dep/4.11/nit-4.11.pdf',
  '/nit/nit-dep/4.12/nit-4.12.pdf',
  '/org/viti/viti-engine/5.1/viti-engine-5.1.pdf',
  '/org/viti/viti-spring/5.1/viti-spring-5.1.pdf'
];
var parentObject = {}
myArray.forEach(res => {
  res = res.slice(1, res.length);
  var array = res.split("/");
  array.forEach((e, i) => {
    ........ // here I am confused 

  });
})
Run Code Online (Sandbox Code Playgroud)

final output should be

parentObject = {
  'unit': {
    'unit': {
      '225': {
        'unit-225.pdf': []
      }
    }
  },
  'nit': {
    'nit-dep': {
      '4.11': {
        'nit-4.11.pdf': []
      },
      '4.12': {
        'nit-4.12.pdf': []
      }
    }
  },
  'org': {
    'viti': {
      'viti-engine': {
        '5.1': {
          'viti-engine-5.1.pdf': []
        }
      },
      'viti-spring': {
        '5.2': {
          'viti-engine-5.2.pdf': []
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 3

用斜杠分割后,使用reduce迭代到嵌套对象,如果需要,首先创建每个嵌套属性,然后将一个数组分配给 filename 属性:

const myArray = [
  '/unit/unit/225/unit-225.pdf',
  '/nit/nit-dep/4.11/nit-4.11.pdf',
  '/nit/nit-dep/4.12/nit-4.12.pdf',
  '/org/viti/viti-engine/5.1/viti-engine-5.1.pdf',
  '/org/viti/viti-spring/5.1/viti-spring-5.1.pdf'
];
var parentObject = {}
myArray.forEach((str) => {
  const props = str.slice(1).split('/');
  const filename = props.pop();
  const lastObj = props.reduce((a, prop) => {
    if (!a[prop]) {
      a[prop] = {};
    }
    return a[prop];
  }, parentObject);
  lastObj[filename] = [];
});
console.log(parentObject);
Run Code Online (Sandbox Code Playgroud)