首页 > 解决方案 > How do I add new field in existing JSON

问题描述

I have JSON with 10000 unique records and I need to add another field with a unique value to every record. How do I add that?

[
{
_id: "5fffd08e62575323d40fca6f",
wardName: "CIC",
region: "ABC",
location: "AAA",
specialism: "CSR",
__v: 0
},
.
.
.
]

The JSON is stored in variable showWard. How do I add an action field in my JSON with value = './wardName' where wardName is already a field in my JSON? This is my current code:

app.get('/wards', function (req, res) {
    Ward.find({}, function (err, showWard) {
        if (err) { console.log(err); return; }
        return res.send(showWard);
    });
});

标签: javascriptnode.jsjsonexpressparsing

解决方案


使用.map()? 我不知道确定性别的逻辑,但在Ward.find()回调中你可以添加这样的东西:

app.get('/wards', function (req, res) {
    Ward.find({}, function (err, showWard) {
        if (err) { console.log(err); return; }

        const newShowWard = showWard.map(ward => {
            ward.gender = "BOH"; 
            return ward;
        })
        
        return res.send(newShowWard);
    });
});

推荐阅读