在数组中的每个对象提交后,向其添加递增ID属性 [英] Add an incrementing ID property to each object in array after it has been submitted

查看:25
本文介绍了在数组中的每个对象提交后,向其添加递增ID属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在从输入文本区域提交数组中的每个对象后,将唯一的ID属性添加到该数组中。当我在添加更多条目时console.log数组时,它看起来是这样的:

[{"title":"hello","text":"sir"}]

我当前正在使用两个常量变量。注释数组的内容将写入db.json文件。

const notes = []; 
const newID = 0;
这是一个快速js程序,下面是我必须将输入数据写入适当文件的函数。我想为每个条目添加ID,最好是在此函数中。

app.post("/api/notes", (req, res) => {
    let newNote = req.body;
    notes.push(newNote)
    fs.writeFile(path.join(__dirname, 'db/db.json'), JSON.stringify(notes), (err) => {
        if (err) throw err;
      });
    res.end();
});

我已尝试映射新属性,但未成功。我还尝试了forEach遍历数组以添加id++。

如果我这里遗漏了什么相关信息,请告诉我。提前感谢您的帮助/反馈!

推荐答案

我计算出了ForEach,工作代码如下。

app.post("/api/notes", (req, res) => {
    let newNote = req.body;
    notes.push(newNote)
    notes.forEach((note, index) => {
        note.id = index + 1;
    });    
    fs.writeFile(path.join(__dirname, 'db/db.json'), JSON.stringify(notes), (err) => {
        if (err) throw err;
      });
    res.end();
});

这篇关于在数组中的每个对象提交后,向其添加递增ID属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆