问题描述
添加这些数组时遇到问题
I am having trouble while adding these array
637301291068030997 => { guildMemberCount: 4,
guildOwnerID: '348832732647784460',
guildOwner: 'Ethical Hacker',
prefix: '.',
guildID: '637301291068030997',
guildName: 'test server 3',
welcomeChannelID: '-' },
(some number) => {other array}
在上述数组中,我收到的 637301291068030997 $
doc.id
变量中的c $ c>编号,其余部分进入 doc.data()
in the above array i am receiving 637301291068030997
number in doc.id
variable and rest is getting in doc.data()
我的代码是这样的
var temp = {}
temp.guilds = [] // after some lines
snapshot.forEach(doc => {
console.log(doc.id, '=>',doc.data()); // output is above array shown
temp.guilds.push(doc.id = doc.data()) // output of this line is given below this code
})
这是 temp.guilds.push
的输出,丢失的值是 doc.id
或 637301291068030997
here is output of temp.guilds.push
the missing value is doc.id
or 637301291068030997
{ guilds:
[ { guildID: '637301291068030997',
guildName: 'test server 3',
welcomeChannelID: '-',
guildMemberCount: 4,
guildOwnerID: '348832732647784460',
guildOwner: 'Ethical Hacker',
prefix: '.' },
{} // this missing thing before {} is (some number) also bracket is empty by the way so no worries
]
}
我该怎么办,这样我将得到类似的输出
what can i do so that i will get the output like below in a variable
{
"637301291068030997": [
{
"guildMemberCount": 4,
"guildOwnerID": "348832732647784460",
"guildOwner": "Ethical Hacker",
"prefix": ".",
"guildID": "637301291068030997",
"guildName": "test server 3",
"welcomeChannelID": "-"
}
]
}
将临时文件保存到文件中的问题
Issue in saving to the temp to the file file
await fs.writeFileSync ("./data/json/serversettings.json", JSON.stringify(temp), function(err) {
if (err) throw err;
console.log('done');
})
节省了很多钱
{"guilds":[]}
不保存其中的任何内容,但 console.log(temp)
给出正确的输出
not saving anything inside it but console.log(temp)
is giving correct output
推荐答案
使用 doc.id = doc.data()
,您正在将数据分配给 id
属性。那不是您想要的。
With doc.id = doc.data()
you are assigning the data to the id
property. That cannot be what you want.
我建议根本不要创建一个数组,而是创建一个简单的(嵌套的)对象。
I would suggest to not create an array at all, but a plain (nested) object.
就像这样:
// ...
temp.guilds = {} // plain object, not array
snapshot.forEach(doc => {
temp.guilds[doc.id] = doc.data();
})
如果 snapshot.forEach
实现实现了异步回叫,则请确保等待所有回调完成后,再依赖 temp.guilds
的内容。承诺可以减轻这项任务。
If the snapshot.forEach
implementation makes the call backs asynchronously, then make sure to wait until all call backs have been made before relying on the contents of temp.guilds
. Promises can ease that task.
// ...
let promise = new Promise(function(resolve) {
let guilds = {} // plain object, not array
let remaining = snapshot.size; // If firebase, there is this property
snapshot.forEach(doc => {
guilds[doc.id] = doc.data();
remaining--;
if (!remaining) resolve(guilds);
});
});
promise.then(function (guilds) {
// do anything you like with guilds inside this function...
let temp = { guilds };
// ...
});
这篇关于如何将这些值添加到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!