【问题标题】:Referring the object in JSON and what is nested引用 JSON 中的对象以及嵌套的内容
【发布时间】:2020-05-21 21:36:55
【问题描述】:

我目前正在尝试通过发送以下 JSON 对象执行 HTTP 发布请求来测试我的后端。我可以在 React 中引用“NPG”和“name”键及其值的唯一方法是我执行 console.log(req.body.NPG) 和 console.log(req.body.NPG.name)。问题在于,如果不是像“SPG”那样发送“NPG”,那么我的控制台日志会给我一个未定义的错误。我如何泛指“NPG”?我尝试做 console.log(req.body.object) 但我仍然有未定义的错误。我的最终目标是将 JSON 对象保存到 MongoDB 集合中。

\\JSON object
{
  "NPG":{
    "name": "North Parking Garage",
    "desc" "6-story parking structure located on the corner of S. 10th and E.  San Fernando Streets"
  }
}

\\My Model Schema

const testSchema = new Schema({
  object: {
    name: String,
    desc: String,
})

【问题讨论】:

    标签: json reactjs react-router


    【解决方案1】:

    以下代码不会中断。

    req && req.body && req.body.NPG && console.log(req.body.NPG.name);
    
    for SPG
    
    req && req.body && req.body.SPG && console.log(req.body.SPG.name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-29
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2011-01-07
      • 2011-12-09
      • 2014-08-28
      • 2013-01-04
      相关资源
      最近更新 更多