简体   繁体   English

创建新的而不是覆盖

[英]Creating new instead of overwriting

Hi!你好!

I'm creating a warn system and I want to save warns to JSON file.我正在创建一个警告系统,我想将警告保存到 JSON 文件中。 The problem is that when I'm trying to make a new object in something it overwrites.问题是当我试图在它覆盖的东西中制作一个新的 object 时。

My code:我的代码:

const warnObject = JSON.parse(fs.readFileSync('./data/data.json'));
const id = "739176"
const length = Object.keys(warnObject[id]).length + 1

warnObject[id] = {}
warnObject[id][length] = {}
warnObject[id][length]["reason"] = "This is a reason."
warnObject[id][length]["date"] = new Date().toLocaleString(); 
fs.writeFileSync('./data/data.json', JSON.stringify(warnObject));

And here's my JSON file:这是我的 JSON 文件:

{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}

So I want to instead of overwriting warn number 2 create new like this所以我不想覆盖警告号 2,而是像这样创建新的

{"739176":{"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}, {"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}}

If you want to have multiple warning objects under the id "739176", you would need to format your json file in order to have an array associated to your id, such as:如果你想在 id“739176”下有多个警告对象,你需要格式化你的 json 文件,以便有一个数组与你的 id 相关联,例如:

{
  "739176":[
      {"2":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}},
      {"3":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}}
  ]
}

So, once you have formatted your file this way, you will be able to get the array referred by the id, and push objects to it like this:所以,一旦你以这种方式格式化了你的文件,你将能够获得由 id 引用的数组,并将对象推送到它,如下所示:

warnObject[id].push({"4":{"reason":"This is a reason.","date":"28.03.2022, 14:52:09"}});

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

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