【问题标题】:Create a object i an object based on the array of string value根据字符串值数组创建对象 i 对象
【发布时间】:2019-09-13 20:58:43
【问题描述】:

我需要根据字符串值的数组来更新对象名称,最后一个字符串值应该是一个数组。

我使用 array.forEach 循环,但如果对象存在并且 myArray 包含大约 10,000 个字符串,我不知道如何在对象中找到该对象。

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 

  });
})

最终输出应该是

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': []
        }
      }
    }
  }
}

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    用斜线分割后,使用reduce 迭代嵌套对象,如有必要,首先创建每个嵌套属性,然后将数组分配给文件名属性:

    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);

    【讨论】:

      【解决方案2】:

      您也可以减少数组并减少路径。最后分配数组。

      const
          array = ['/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'],
          result = array.reduce((r, path) => {
              var keys = path.split(/\//).slice(1),
                  last = keys.pop();
      
              keys.reduce((o, k) => o[k] = o[k] || {}, r)[last] = [];
              return r;
          }, {});
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      稍微快一点的方法。

      const
          array = ['/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'],
          result = {};
      
      for (let path of array) {
          let keys = path.split(/\//).slice(1),
              last = keys.pop(),
              temp = result;
      
          for (let key of keys) {
              temp[key] = temp[key] || {};
              temp = temp[key];
          }
          temp[last] = [];
      }
      
      console.log(result);
      .as-console-wrapper { max-height: 100% !important; top: 0; }

      【讨论】:

        【解决方案3】:

        您也可以采用递归方法。

        继续移动拆分路径,直到获得每个分支的最终分配。

        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'
        ];
        
        console.log(buildTree(myArray));
        
        function buildTree(list=[]) {
          return list.reduce((node, item) => buildBranches(node, item.split(/\//g).filter(x => x !== '')), {});
        }
        
        function buildBranches(node={}, rest=[]) {
          let key = rest.shift();
          node[key] = rest.length < 2 ? { [rest.shift()] : [] } /** or rest.shift() */ : node[key] || {};
          if (rest.length > 1) buildBranches(node[key], rest);
          return node;
        }
        .as-console-wrapper { top: 0; max-height: 100% !important; }

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-07
          • 2019-07-30
          • 1970-01-01
          • 2021-10-25
          • 2020-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多