【发布时间】: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