javascript – 从键/值对创建复杂对象

我有一个具有键/值对的文件.该文件通过Docker加载到process.env中.但是出于开发目的,我手动加载它,所以最后它们是相同的;

配置:

process.env['ccc.logger.winston.level']='info';
process.env['ccc.logger.winston.transports.type.file']='File';
process.env['ccc.logger.winston.transports.filename']='logs/testOne.log';
process.env['ccc.logger.winston.transports.rotate']='false';

process.env['ccc.logger.winston.transports.type.file']='File';
process.env['ccc.logger.winston.transports.filename']='logs/testTwo.log';
process.env['ccc.logger.winston.transports.rotate']='true';

我的期望是拥有这个目标:

{
  "ccc": {
    "logger": {
      "winston": {
        "level": "info","transports": [
          {
            "type": "File","filename": "logs/testONE.log","rotate": true
          },{
            "type": "File","filename": "logs/testTWO.log","rotate": false
          }
        ]
      }
    }
  }
}

我已经提出了可行的解决方案,但如果我有一个对象数组,我遇到了问题,就像上面的例子一样:

循环所有键/值的函数和调用函数来创建对象:

let ENV_FROM_DOCKER = process.env;

for (let property in ENV_FROM_DOCKER) {
  let checkForShallowProperties = property.split(".")[1];

  if (typeof checkForShallowProperties === 'undefined') {
    continue;
  }

  let resultObject = this.expand(property,ENV_FROM_DOCKER[property]););

  emptyConfig = merge(emptyConfig,resultObject);
  let stop;
}

对象创建功能:

expand(str,value) {
  let items = str.split(".") // split on dot notation
  let output = {} // prepare an empty object,to fill later
  let ref = output // keep a reference of the new object

  //  loop through all nodes,except the last one
  for (let i = 0; i < items.length - 1; i++) {
    ref[items[i]] = {}; // create a new element inside the reference
    ref = ref[items[i]]; // shift the reference to the newly created object
  }

  ref[items[items.length - 1]] = value; // apply the final value
  return output // return the full object
}

这个设置工作正常,但如果我有一个对象数组的对象(如上面的例子),它不能正常工作.这是现在的输出:

{
  "ccc": {
    "logger": {
      "winston": {
        "level": "info","transports": {
          "type": {
            "file": "File"
          },"filename": "logs/testTwo.log","rotate": "true"
        }
      }
    }
  }
}

我试图让这段代码现在工作几个小时,但只是在圈子里旋转. ccc对象就是一个例子.键/值列表中还有其他对象也可能包含数组.

最佳答案
为每个传输分配索引

在创建环境变量时,您可以将每个transports.whatnot分配给数组中的索引传输[0] .whatnot和transports [1] .whatnot.为了完成这项工作,我们必须像这样解析它:

const ENV = {
  'ccc.logger.winston.level': 'info','ccc.logger.winston.transports[0].type': 'File','ccc.logger.winston.transports[0].filename': 'logs/testOne.log','ccc.logger.winston.transports[0].rotate': 'false','ccc.logger.winston.transports[1].type': 'File','ccc.logger.winston.transports[1].filename': 'logs/testTwo.log','ccc.logger.winston.transports[1].rotate': 'true'
}

for (let property in ENV) {
  let checkForShallowProperties = property.split('.')[1]; 

  if (typeof checkForShallowProperties === 'undefined') {
    continue;
  }

  let resultObject = expand(property,ENV[property])
  console.log(resultObject)
}

function expand(string,value) {
  const items = string.split('.').map(name => {
    const match = name.match(/\[\d+?\]/)
    return {
      name: match ? name.slice(0,match.index) : name,usesBrackets: !!match,key: match && match[0].slice(1,-1)
    }
  })
  
  const output = {}
  let ref = output
  let parent
  
  for (const item of items) {
    ref[item.name] = {}
    parent = ref
    ref = ref[item.name]
    if (item.usesBrackets) {
      ref[item.key] = {}
      ref = ref[item.key]
    }
  }
  parent[items[items.length - 1].name] = value
  return output
}

这里的输出是PRE-MERGE

正如您所看到的,它的工作方式是将对象视为自己的数组,并将内容放在索引或甚至其他访问器中.

但是,将所有这些转移到.json文件或某个内容管理系统最有可能符合您的最佳利益,因为这是一种非常不稳定的处理方式.如果您的需求发生了变化,您可能需要重写它,使用JSON您只需加载JSON即可.

相关文章

文章浏览阅读8.8k次,点赞2次,收藏7次。本文介绍Docker Com...
文章浏览阅读1.5w次,点赞7次,收藏76次。原网提供的教程需要...
文章浏览阅读940次,点赞20次,收藏20次。通过 docker run 命...
文章浏览阅读1k次,点赞20次,收藏20次。Podman 是一个开源的...
文章浏览阅读2.1k次。请注意,这些命令需要在 Docker 主机上...
文章浏览阅读1.1k次,点赞37次,收藏40次。nacos搭建集群连接...