Blue
Blue

Reputation: 1448

Concatenating JSON objects in Nodejs

I'm pull data from my data base and converting into to JSON but now I want to place all the JSON data into a single JSON object. I've tried a few methods but I'm not familiar enough with the syntax of javascript and have been unable to find a working solution with proper formatting. I'd like to simply have and object(or two) and continuously add add the new JSON to the older object. I'd prefer not to important any modules for this.

.then(querySnapshot => {
        querySnapshot.forEach(documentSnapshot => {
                myData2 = myData.concat(receiptToDict(documentSnapshot));
                console.log("Found document at", myData2);

            });

});

Upvotes: 0

Views: 209

Answers (2)

Charles Assuncao
Charles Assuncao

Reputation: 568

You can either

var myData2 = Object.assign({}, myData, receiptToDict(documentSnapshot))

or

var myData2 = { ...myData, ...receiptToDict(documentSnapshot) }

EDIT

If you consider the loop, consider you myData declaration outside of the loop and then:

var myData = {};
   ...
.then(querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
        myData = Object.assign({}, myData, receiptToDict(documentSnapshot))
        console.log("Found document at", myData);
        });

});

2 EDIT

A object can't have the same property twice, so if you have something like

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

You will end up replacing always the prop "value"so in this case you should do something like:

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

});

Upvotes: 2

halbertino
halbertino

Reputation: 1

myData looks like an Array, so you could do:

.then(querySnapshot => {
        querySnapshot.forEach(documentSnapshot => {
               myData.push(receiptToDict(documentSnapshot));

            });

});

Upvotes: 0

Related Questions