简体   繁体   English

如何将json对象列表转换为javascript对象列表?

[英]How do you convert a list of json objects to a list of javascript objects?

I am currently running into a problem while developing a small web app. 我目前在开发小型Web应用程序时遇到问题。 I want to send a query to my API from my react front end to ask for a list of "devices" from my MongoDB database. 我想从我的React前端向我的API发送查询,以从MongoDB数据库中获取“设备”列表。 My API endpoint correctly gets that data from the database. 我的API端点正确地从数据库中获取了该数据。 However, when I send it back to the front end I run into a problem where I just have a list of "[Object object]"'s and I don't know how to convert this to a list of javascript objects that I can use to render each object in the list into a react component. 但是,当我将其发送回前端时,遇到了一个问题,我只有一个“ [Object object]”的列表,而且我不知道如何将其转换为我可以使用的javascript对象列表用于将列表中的每个对象渲染为react组件。 Anyone know how I can do this? 有人知道我该怎么做吗?

I've tried to use a variety of combinations of json.parse and json.stringify but I still cant figure out how to properly get these results into a react component. 我试图使用json.parse和json.stringify的各种组合,但是我仍然无法弄清楚如何正确地将这些结果转换为react组件。

My API endpoint: 我的API端点:

app.get("/api/getdeviceinfo", function(req, res) {
  let token = req.cookies.token;
  let decoded = jwt.decode(token);
  let email = decoded.email;
  let devices = DeviceInfo.find({}).exec(function(err, results) {
    if (err) {
      res.send("an error has occured");
    } else {
      console.log(results);
      res.json(results);
    }
  });
});

A clip from my frontend: 我前端的剪辑:

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      deviceInfo: []
    };
  }

  componentDidMount() {
    fetch("/api/getdeviceinfo", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(res => res.json())
      .then(data => {
        let info = JSON.stringify(data);
        let infoData = JSON.parse(info);
      })
      .catch(err => {
        console.error(err);
        alert("Error logging out\n" + err);
      });
  }

I would like to have this json list of results from my database be a list of javascript objects but instead I have a list of [Object object]'s. 我希望数据库中的json结果列表是javascript对象的列表,但我却有[Object object]的列表。

Update: 更新:

When I use the following code the resulting alert displays [object Object], [object Object], [object Object], [object Object], [object Object]: 当我使用以下代码时,生成的警报显示[对象对象],[对象对象],[对象对象],[对象对象],[对象对象]:

componentDidMount() {
    fetch("/api/getdeviceinfo", {
      method: "GET",
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(res => res.json())
      .then(data => {
        alert(data);
      })
      .catch(err => {
        console.error(err);
        alert("Error logging out\n" + err);
      });
  }

This is the correct number of items in the list. 这是列表中正确的项目数。 But how do I get the attributes from each object? 但是,如何从每个对象获取属性?

There's a couple of problems here. 这里有两个问题。 The first is that you're calling res.json() without passing the object. 第一个是您在不传递对象的情况下调用res.json()。 Second is that the "res" object is not really the data. 其次,“ res”对象不是真正的数据。 It's a cyclic object You either need to destructure like so (if the data is truly in the .data property of that object you could check by calling console.log(JSON.stringify(res)) to get a look): 这是一个循环对象,您要么需要像这样进行解构(如果数据确实位于该对象的.data属性中,则可以通过调用console.log(JSON.stringify(res))进行检查):

.then(({data}) => res.json(data)

or access the property of data from the res 或从资源库访问数据的属性

res.data

Another note. 另一个说明。 I'm not all that familiar with the fetch api. 我对提取API不太熟悉。 I use axios. 我使用axios。 I don't believe there is a res.json() method on that object like there is with express or other libraries. 我不认为该对象上有res.json()方法,例如express或其他库。 do a console log or debug into that .then and check... 做一个控制台日志或调试到。然后检查...

.then(res => console.log(JSON.stringify(res))

You may just want to destructure and set your state with it. 您可能只想破坏结构并使用它来设置状态。 I realize this is incomplete because of my lack of knowledge here so if there's an issue with that i'll happily delete this answer. 我意识到这是不完整的,因为我在这里缺乏知识,因此,如果有任何问题,我会很乐意删除此答案。 Just trying to get you unstuck mate! 只是想让你陷入困境的队友!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM