我正在从数据库中提取数据并将其转换为JSON,但现在我想将所有JSON数据放入单个JSON对象中。我尝试了几种方法,但是我对javascript的语法不熟悉,并且无法找到格式正确的有效解决方案。我只想拥有和对象(或两个)并不断添加,即可将新的JSON添加到较旧的对象中。我不想为此而忽略任何模块。
Classes ‘data.table’ and 'data.frame': 1 obs. of 2 variables:
$ x: num 1
$ y:List of 1
..$ : num 1 1
- attr(*, ".internal.selfref")=<externalptr>
答案 0 :(得分:2)
您可以
var myData2 = Object.assign({}, myData, receiptToDict(documentSnapshot))
或
var myData2 = { ...myData, ...receiptToDict(documentSnapshot) }
编辑
如果考虑循环,请在循环之外考虑myData声明,然后:
var myData = {};
...
.then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
myData = Object.assign({}, myData, receiptToDict(documentSnapshot))
console.log("Found document at", myData);
});
});
2编辑
一个对象不能具有相同的属性两次,所以如果您有类似的东西
let myData = {};
let dataArray = [
{value: 01},
{value: 02},
{value: 03},
{value: 04},
{value: 05}
]
dataArray.forEach((data) => {
myData = Object.assign({}, myData, data)
})
console.log(myData);
您最终将总是替换属性“值”,因此在这种情况下,您应该执行以下操作:
var myData = {};
...
.then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
//I don't know which props you obj has so, I suppose it has a unique id for example
let doc = receiptToDict(documentSnapshot);
myData[doc.id] = doc;
console.log("Found document at", myData);
});
});
答案 1 :(得分:0)
myData
看起来像一个数组,所以可以这样做:
.then(querySnapshot => {
querySnapshot.forEach(documentSnapshot => {
myData.push(receiptToDict(documentSnapshot));
});
});