【问题标题】:Preserving Object Data保留对象数据
【发布时间】:2020-04-22 12:02:20
【问题描述】:

我正在创建一个程序,用户可以在其中保留会话之间的搜索词。如果用户保留了搜索词,则与该搜索词对应的数据也被保留。在每个会话开始时,如果这些旧数据不再对应于活动或连接的驱动器,该脚本会丢弃所有应保留的旧数据。

但是,我通常是使用 JSON 和此类对象的新手,所以我想知道是否有比以下方法更好的方法来完成此操作?具体来说,有没有比第一个 for of 循环和重度嵌套的 if,for,for,if 代码块更高效甚至更漂亮的方法?

async function guaranteeData(drives){
  const
    config = await readJson('./config.json'),
    data = await readJson('./data.json')


  // Is there a better way to write this code?

  let
    json = {}

  for (const [drive] of drives) {
    json[drive] = {}
  }

  // if tags have been preserved
  if (config.fileTypes.length > 0) {
    // loop thru all current system drives
    for (const [drive] of drives) {
      // loop thru all preserved tags
      for (const fileType of config.fileTypes) {
        // if current drive has current tag data
        if (data[drive].hasOwnProperty(fileType)) {
          // preserve this data: data[drive][fileType]
          json[drive][fileType] = data[drive][fileType]
        }
      }
    }
  }

  ////////////////////////////////////////////


  json = JSON.stringify(json, null, 2)
  await fsp.writeFile('./data.json', json, {
    flag: 'w',
    encoding: 'utf8'
  })
  .then(() => {
    return true
  })
  .catch(error => {
    if (error.code === 'EEXIST') {
      return false
    } else {
      throw error
    }
  })
}

【问题讨论】:

  • 对我来说看起来很合理,尽管您可以完全省略 if (config.fileTypes.length > 0) { 部分,因为如果长度为 0,for (const fileType of config.fileTypes) { 根本不会执行任何迭代
  • @CertainPerformance 好点!!除了嵌套的for/of/if 代码块,没有更好的替代方案了吗?
  • 所需的逻辑涉及嵌套循环和嵌套循环内的条件操作,因此无法绕过那里的基本嵌套
  • @CertainPerformance 好的,感谢您的帮助。发布您的答案并接受它。

标签: javascript node.js json object nested


【解决方案1】:

我将在此更改两件事

  • 删除 if (config.fileTypes.length > 0) 检查,因为它将在之后的 for 循环中处理。

  • 删除将json[drive] 分配给嵌套for 循环的for 循环内的空对象的for 循环。这也将删除该 for 循环。

它看起来像

async function guaranteeData(drives) {
  const config = await readJson("./config.json");
  const data = await readJson("./data.json");

  const json = {};

  // if tags have been preserved
  // loop thru all current system drives
  for (const [drive] of drives) {
    json[drive] = {};
    // loop thru all preserved tags
    for (const fileType of config.fileTypes) {
      // if current drive has current tag data
      if (data[drive].hasOwnProperty(fileType)) {
        // preserve this data: data[drive][fileType]
        json[drive][fileType] = data[drive][fileType];
      }
    }
  }

  ////////////////////////////////////////////

  json = JSON.stringify(json, null, 2);
  await fsp
    .writeFile("./data.json", json, {
      flag: "w",
      encoding: "utf8"
    })
    .then(() => {
      return true;
    })
    .catch(error => {
      if (error.code === "EEXIST") {
        return false;
      } else {
        throw error;
      }
    });
}

【讨论】:

    猜你喜欢
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    相关资源
    最近更新 更多