如何发布内部包含对象数组的数组?

时间:2019-12-21 22:43:58

标签: javascript node.js json express

语境

我正在学习JavaScript,同时使用node.JS和express构建REST API。目前,我一直试图读取具有对象数组的对象数组。以下是我正在阅读的内容的一个小示例。

[
    {
        "description":"hhhh",
        "goal":"yyyy",
        "goalDate":"12/5/2019",
        "mSubGoalArray":
            [
                {
                    "description":"yyyy",
                    "goal":"ggggg",
                    "goalDate":"12/4/2019",
                    "mSubGoalArray":[]
                }
            ]
    },
    {
        "description":"yy",
        "goal":"gg",
        "goalDate":"12/11/2019",
        "mSubGoalArray":
            [
            ]
    }
]

我尝试过的东西

我尝试将其-> bodyParser.urlencoded({extended:true})设置为true,然后只读取完整的字符串。当我显示在VIA邮递员中读取的数据时,它会显示已被读取并识别,但是无法在控制台中显示,它显示为undefined

我还尝试模仿对象中包含的所有字段,并且一次只读取它们。但是,当我与API进行交互时,这会编译,最终收到一个数组,提示初始化前无法访问“目标”。

goals.js

const express = require('express');
const router = express.Router();

//getting from the database
router.get('/', (req, res, next) => {

});

//posting to the database
router.post('/', (req, res, next) => {

    const Array = req.body.data;
    console.log(Array);

    /*const goal = [
        goal.description = req.body.description,
        goal.goal = req.body.goal,
        goal.goalDate = req.body.description,
        goal.mSubGoalArray = [
            mSubGoalArray.description = req.body.description,
            mSubGoalArray.goal = req.body.goal,
            mSubGoalArray.goalDate = req.body.description,
            mSubGoalArray.mSubGoalArray['null'],
        ]
    ];*/

    res.status(200).json({
        the: 'Updated goal'
    });
});

module.exports = router;

app.js

const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

const goalsRoutes = require('./api/routes/goals');
const loginRoutes = require('./api/routes/login');

app.use('/goals', goalsRoutes);
app.use('/login', loginRoutes);

module.exports = app;

问题#

我知道bodyparser应该允许内部对象。如何显示读取的JSON对象,以便可以确认已成功传输该对象?如何摆脱错误目标初始化错误的另一种方式。

1 个答案:

答案 0 :(得分:1)

router.post('/', (req, res, next) => {

    const tab= req.body;
    console.log(Array);
tab.forEach(element=>{

//HERE WE ARE LOOPING ON THE FIRST ARRAY NOW YOU ACCESS TO THE DATA FOR EXAMPLE element.description element.goal and you can also loop inside this loop on the element.mSubGoalArray

})


    res.status(200).json({
        the: 'Updated goal'
    });
});