从键/值对创建复杂对象

韦克索尼

我有一个包含键/值对的文件。该文件process.env通过Docker加载到内部但是出于开发目的,我是手动加载它的,因此最后它们是相同的。

配置:

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数组transports[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即可

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章