提交后为数组中的每个对象添加一个递增的 ID 属性
Add an incrementing ID property to each object in array after it has been submitted
我试图在数组中的每个对象从输入和文本区域提交后添加一个唯一 ID 属性。当我 console.log 数组添加更多条目时,它看起来像这样:
[{"title":"hello","text":"sir"}]
我目前正在使用两个 const 变量。音符数组的内容被写入 db.json 文件。
const notes = [];
const newID = 0;
这是一个 express 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++。
如果我在这里缺少任何相关信息,请告诉我。提前感谢任何 help/feedback!
我找到了 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 属性。当我 console.log 数组添加更多条目时,它看起来像这样:
[{"title":"hello","text":"sir"}]
我目前正在使用两个 const 变量。音符数组的内容被写入 db.json 文件。
const notes = [];
const newID = 0;
这是一个 express 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++。
如果我在这里缺少任何相关信息,请告诉我。提前感谢任何 help/feedback!
我找到了 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();
});