gpt4 book ai didi

javascript - JSON Stringify 使一个对象键值为空的对象数组

转载 作者:行者123 更新时间:2023-11-29 18:49:18 25 4
gpt4 key购买 nike

谁能帮我解决这个问题,我正在努力实现这样的目标:

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

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

let query = { docs: [] };

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

{ _id: item }

我在 forEach 循环中将其推送到文档中

 query.docs.push(item);

所以当我去字符串化的时候

JSON.stringify(query);

它返回对象但数组为空。

{ "docs": [] }

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

Actual code:

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));

This is the server response:

enter image description here

最佳答案

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

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));
});

关于javascript - JSON Stringify 使一个对象键值为空的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51876697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com