0
votes

I am reading document from collection and storing 2 different variables. But whenever I remove any key from the JSON it affects first variables result.

I want to keep both of them independent so that change of one will not reflect other.

var query =  'SELECT * FROM c where c.id = "XYZ" 

var accept = collection.queryDocuments(collection.getSelfLink(), filterQuery,   
            function (err, documents, responseOptions) 
            {
                if (err) throw new Error("Error" + err.message);  

                if (documents.length != 1) 
                    throw "Document Not Exist"; 
                else
                {
                    var doc1 = new Object;
                    var doc2 = new Object;

                    doc1 =  documents[0];
                    doc2 =  documents[0];
                    var i = doc1.abc[0].pqr;

                    for(x = 0; x < doc1.abc[0].pqr.length; x++)
                    {
                        delete doc1.abc[0].pqr[x];
                    }
                    console.log(doc2)
                }

Here console.log(doc2) also not showing the deleted elements which I want.

1

1 Answers

0
votes

doc1.abc[0] and doc2.abc[0] represent the same object, they are the same reference. See this for some more information on what this means.

If you want to modify the two documents idependently, you need to seperate the data completely.

This is probably the simplest way:

 var doc1 =  documents[0];
 var doc2 = JSON.parse(JSON.stringify(doc1));

(Source: How to copy JavaScript object to new variable NOT by reference?)