Combining JavaScript Objects in Couchdb

I have this Couchdb view that doesn't do what I expect. It does not add code , balance and session to params :

 function(doc) { var params = doc.initial_url_params; //This is an object with many properties params["code"] = doc.code; params["balance"] = doc.balance; params["session"] = doc.session.session_id; emit(doc.code, params); } 

On the other hand, this other implementation does the trick:

 function(doc) { var params = {}; params["code"] = doc.code; params["balance"] = doc.balance; params["session"] = doc.session.session_id; for (prop in doc.initial_url_params) { params[prop] = doc.initial_url_params[prop]; } emit(doc.code, params); } 

Can someone tell me why these two implementations are not equivalent? Am I doing something stupid with Javascript or is it some specific limitation of the implementation of Couchdb Javascript?

For clarity. Here is a json doc example:

 { "_id": "207112eaaad136dca7b0b7b1c6356dc4", "_rev": "3-e02de1f2f269642df98ab19ee023569b", "session_loaded": true, "balance": 20.48, "code": "05428", "initial_url_params": { "page_id": "212" }, "session": { "session_id": "207112eaaad136dca7b0b7b1c6356dc4", "init": true } } 
+4
source share
1 answer

The difference in your 2 selections is that initial_url_params is a property of an already defined doc object that may have been frozen before proceeding with your function. Thus, you cannot add new properties to it, but you can still read and iterate over them to create a new (unfrozen) object.

And this is similar to the case of OP related thread .


In JavaScript, objects are passed by reference, so if properties are to be added to the doc object, all other functions that work on it will also be able to see these non-standard properties and possibly violate some map functions.

Here's a vanilla JS example of the above paragraph:

 var doc = { foo: true }; function a(doc) { doc.bar = 1; } function b(doc) { console.log(doc); } a(doc); b(doc); // outputs: { foo: true, bar: 1 } 

Demo - in the above example, b expects to see only the initially defined properties in the doc , but a changed it because the objects are passed by reference. This is an oversimplified view, but you can see what it can do when a function tries to map the properties of an object to a different logic.

+2
source

All Articles