繁体   English   中英

在Javascript中从嵌套对象创建字符串路径

[英]Create string paths from nested object in Javascript

我试图将代表我的文件系统的嵌套对象转换为代表每个文件夹和文件的文件路径的字符串数组。

输入:

let obj = {
  'app': {
    'body': {
      'abs': {
        'muscles.txt': 1
      },
      'foot.js': 1,
      'hand.txt': 1,
      'leg.txt': 1
    },
    'cat.txt': 1,
    'dog.js': 1,
    'writing': {
      'pen.txt': 1,
      'phone.txt': 1
    }
  }
};

输出:

  [
  '/app', 
  '/app/body',
  '/app/body/abs/',
  '/app/body/abs/muscles.txt',
  '/app/body/foot.js',
  '/app/body/hand.txt',
  ...
]

到目前为止我所拥有的(它不起作用):

function filePaths(obj, oldKey = '', store = []) {
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      store.push('/' + key);
      filePaths(obj[key], key, store);
    } else {
      store.push('/' + oldKey + '/' + key);
    }
  }
  return store;
}

filePaths(obj);

这是一个工作版本:

 let obj = { 'app': { 'body': { 'abs': { 'muscles.txt': 1 }, 'foot.js': 1, 'hand.txt': 1, 'leg.txt': 1 }, 'cat.txt': 1, 'dog.js': 1, 'writing': { 'pen.txt': 1, 'phone.txt': 1 } } }; function filePaths(obj, prefix = '', store = []) { for (let key in obj) { const curPath = `${prefix}/${key}`; if (typeof obj[key] === 'object') { store.push(curPath); filePaths(obj[key], curPath, store); } else { store.push(curPath); } } return store; } console.log(filePaths(obj));

所以我保留了你的大部分代码,但改变了这样一个事实,即当你保留“旧”键时,我保留当前路径,它作为所有文件的前缀和所有将获得附加当前密钥。

你在递归的正确轨道上。 对于每次调用,遍历当前对象中的每个属性,为该属性创建一个路径并将其添加到结果数组中。 如果属性键指向一个对象,则它是一个非终端节点,并被递归调用以为其子节点添加路径。

 const pathify = (o, res=[], path=[]) => { for (const dir in o) { const s = path.join("/"); res.push(`/${s ? `${s}/${dir}` : dir}`); if (typeof o[dir] === "object") { pathify(o[dir], res, path.concat(dir)); } } return res; }; const obj = { 'app': { 'body': { 'abs': { 'muscles.txt': 1 }, 'foot.js': 1, 'hand.txt': 1, 'leg.txt': 1 }, 'cat.txt': 1, 'dog.js': 1, 'writing': { 'pen.txt': 1, 'phone.txt': 1 } } }; console.log(pathify(obj));

这是一个递归解决方案,它利用Object.keys方法和扩展运算符concatmap

 let obj = { 'app': { 'body': { 'abs': { 'muscles.txt': 1 }, 'foot.js': 1, 'hand.txt': 1, 'leg.txt': 1 }, 'cat.txt': 1, 'dog.js': 1, 'writing': { 'pen.txt': 1, 'phone.txt': 1 } } }; function filePaths(obj, prefix = "", store = []) { if (typeof obj !== "object") return [prefix]; return (prefix && [prefix] || []).concat(...Object.keys(obj).map(k => filePaths(obj[k], prefix + "/" + k, store))) } console.log(filePaths(obj))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM