【问题标题】:JSON Stringify is making an object key with a value of array of objects emptyJSON Stringify 正在使对象数组的值为空的对象键
【发布时间】:2018-08-16 12:07:01
【问题描述】:

有人可以帮我解决这个问题吗,我正在尝试实现这样的目标:

{ "docs": [
{ "_id": "item" },
{ "_id": "item" },
{ "_id": "item" }
] }

所以我从一个带有关键文档的对象开始,这是一个我将推入的数组

let query = { docs: [] };

然后我有这样的键值对项目列表,大约 80:

{ _id: item }

我在 forEach 循环中推入文档

 query.docs.push(item);

所以当我去字符串化时

JSON.stringify(query);

它返回对象但数组为空。

{ "docs": [] }

我不知道为什么会这样。任何人都知道解决此问题以达到预期结果的方法吗?提前致谢

实际代码:

let elasticQuery = {
    docs: []
  };

  axios({
    method: "post",
    headers: {
      "Content-Type": "application/json"
    },
    url: sent2VecUrl,
    data: {
      selected_text: query
    }
  }).then(results => {
    results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
    });
  });


  console.log("without: " + elasticQuery + " with stringify :" + JSON.stringify(elasticQuery));

这是服务器响应:

【问题讨论】:

  • 这看起来不错,你能告诉我们实际的代码吗?
  • 响应中有什么内容?
  • 问题是JSON.stringify(elasticQuery)results.data.response.forEach......之前执行,在你将push值放入elasticQuery.docs数组之前。

标签: javascript arrays json object


【解决方案1】:

将您的控制台移入 .then 函数。这是异步调用,在您的承诺得到解决之前,您的控制台正在打印。

axios({
method: "post",
headers: {
  "Content-Type": "application/json"
},
url: sent2VecUrl,
data: {
  selected_text: query
}})
.then(results => {
   results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
   });
   console.log("without: " + elasticQuery + " with stringify :" + JSON.stringify(elasticQuery));
});

【讨论】:

  • 谢谢,我将 console.log 移到了那个位置,它确实显示了变化,我完全错过了异步方面。
  • 有一个人发布了答案,但在我接受之前将其删除:(无论如何我认为它现在有效
【解决方案2】:

你的代码看起来不错。

.then(results => {
    results.data.response.forEach(item => {
      elasticQuery.docs.push({ _id: item });
    });

      console.log(elasticQuery); 
  });

【讨论】:

    【解决方案3】:

    而不是这个:

    results.data.response.forEach(item => {
          elasticQuery.docs.push({ _id: item });
    });
    

    这样做:

      elasticQuery.docs = results.data.response.map(item => ({ _id: item }) )
    

    【讨论】:

      猜你喜欢
      • 2019-04-28
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2014-05-26
      • 1970-01-01
      • 2018-05-21
      • 2013-12-17
      • 2016-03-18
      相关资源
      最近更新 更多