首页 > 解决方案 > 为什么将对象发布到 json 文件时,其中一个键/值总是显示为花括号?

问题描述

所以,我有这个表单按钮,当按下时,它会将对象发布到一个名为“notes”的数组中。该对象填充了表单字段值和函数的返回(例如:返回创建日期的函数)。我创建了另一个函数来返回 idm,它基本上是数组“notes”的长度。创建日期返回,在 json 文件中显示正常,但是 id 函数始终显示为花括号。

我怀疑它可能是异步等待键,因为如果我创建简单的函数来返回“hello”,那么在 json 文件中会显示为“hello”。

如果有人知道这一点,我将不胜感激。

发布的对象:

let userNote = { // the object
        noteName: noteNameInput.value,
        important: noteImportant.value,
        reminder: noteDateInput.value,
        noteMsg: noteMsgInput.value,
        creationDate: creationDate(),
        id: id()
    }
let data = JSON.stringify(userNote);

功能:

function creationDate(){
    let today = new Date();
    let day = today.getDate();
    let month = today.getMonth()+1;
    let year = today.getFullYear();
    let currentDate = `${day}/${month}/${year}`;
    return currentDate;
}
function id(){
    return new Promise ((resolve, reject) => {
        setTimeout(async () => {
            const PORT = process.env.PORT || 3001;
            const req = await fetch(`http://localhost:${PORT}/api`);
            const data = await req.json();
            let id_number = (data.notes.length);
            const error = false;
            //------------
            if(!error){
                resolve(id_number);
            } else {
                reject('Something went wrong!');
            }
        }, 1000);
    });
}

json文件(*我在“teste2”之后开始尝试):

{"notes":[{"noteName":"teste1","important":"on","reminder":"2021-10-20","noteMsg":"teste1","creationDate":"7/10/2021"},{"noteName":"teste2","important":"on","reminder":"2021-10-28","noteMsg":"teste2","creationDate":"7/10/2021"},{"noteName":"teste3","important":"off","reminder":"2021-10-21","noteMsg":"teste3","creationDate":"7/10/2021","id":{}},{"noteName":"teste4","important":"off","reminder":"2021-10-19","noteMsg":"teste4","creationDate":"7/10/2021","id":{}},{"noteName":"teste5","important":"off","reminder":"2021-10-21","noteMsg":"teste5","creationDate":"7/10/2021","id":{}},{"noteName":"a","important":"off","reminder":"2021-10-21","noteMsg":"a","creationDate":"7/10/2021","id":{}}]}

*我已经尝试过有和没有承诺,以获得相同的最终结果。(花括号问题)

标签: javascriptreactjsasync-await

解决方案


推荐阅读